我该如何选择一个数字10000并将其输出为$10,000.00?
我什至有String.format(...)一个Not a function错误的问题。
我关注了许多文章,所有文章都不完整,没有任何内容。
我不需要完全的国际化,只需要格式化数字的能力
Mur*_*ray 15
编辑:抱歉 - 这是一个 React.js 解决方案 - 不是 React Native。以上都不适合我......但是这个家伙有正确的想法/解决方案https://medium.com/@nidhinkumar/react-js-number-format-and-styling-a1a6e211e629
const numberFormat = (value) =>
new Intl.NumberFormat('en-IN', {
style: 'currency',
currency: 'INR'
}).format(value);
numberFormat(50000); //output as ? 50,000.00
numberFormat(10000); //output as ? 10,000.00
Run Code Online (Sandbox Code Playgroud)
您可以使用toFixed显示2个小数点的方法。
let num = 1000;
console.log(num.toFixed(2)); // 1000.00
Run Code Online (Sandbox Code Playgroud)
您可以像这样使用Regex
function currencyFormat(num) {
return '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}
console.log(currencyFormat(2665)); // $2,665.00
Run Code Online (Sandbox Code Playgroud)
您可以使用此库react-number-format。具有这些功能
样品用法
<NumberFormat value={2456981} displayType={'text'} thousandSeparator={true} prefix={'$'} />
Run Code Online (Sandbox Code Playgroud)
产出:$ 2,456,981
最快的方法是使用react-number-format,如上所述,但不要忘记 prop,renderText这样 React Native 就不会抛出渲染错误。
请按照以下步骤操作:
npm i react-number-format
Run Code Online (Sandbox Code Playgroud)
import React from 'react';
import NumberFormat from 'react-number-format';
export function ReactNativeNumberFormat({ value }) {
return (
<NumberFormat
value={value}
displayType={'text'}
thousandSeparator={true}
prefix={'$'}
renderText={formattedValue => <Text>{formattedValue}</Text>} // <--- Don't forget this!
/>
);
}
Run Code Online (Sandbox Code Playgroud)
运作良好。正如您所看到的,我最终创建了接受value作为 prop 的自定义组件,这样我就可以在任何需要的地方使用它。像这样:
<View>
<ReactNativeNumberFormat value={530000} />
</View>
Run Code Online (Sandbox Code Playgroud)
希望能有用。
PS:这是我的参考=> https://github.com/s-yadav/react-number-format/issues/17#issuecomment-395187806。
为了避免使用库,您可以使用以下代码
const defaultOptions = {
significantDigits: 2,
thousandsSeparator: ',',
decimalSeparator: '.',
symbol: '$'
}
const currencyFormatter = (value, options) => {
if (typeof value !== 'number') value = 0.0
options = { ...defaultOptions, ...options }
value = value.toFixed(options.significantDigits)
const [currency, decimal] = value.split('.')
return `${options.symbol} ${currency.replace(
/\B(?=(\d{3})+(?!\d))/g,
options.thousandsSeparator
)}${options.decimalSeparator}${decimal}`
}
Run Code Online (Sandbox Code Playgroud)
小智 5
使用 toLocaleString 原生 React 函数:
const formatNumber = (q) => {
return q.toLocaleString('en-US', {
style: 'currency',
currency: 'USD'
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7089 次 |
| 最近记录: |