问题
how do I take a number like 10000 and have it output as $10,000.00?
I even had a problem with String.format(...) with a Not a function error.
I followed numerous articles, all incomplete and none working.
I don't need full internationalization, just the ability to format a number
回答1:
You can use this library react-number-format. It has these features
- Prefix, suffix and thousand separator.
- Custom format pattern.
- Masking.
- Custom formatting handler.
- Format number in an input or format as a simple text
Sample usage
<NumberFormat value={2456981} displayType={'text'} thousandSeparator={true} prefix={'$'} />
Output : $2,456,981
回答2:
You can use toFixed method for showing 2 decimal point.
let num = 1000;
console.log(num.toFixed(2)); // 1000.00
And you can use Regex like this
function currencyFormat(num) {
return '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}
console.log(currencyFormat(2665)); // $2,665.00
回答3:
None of the above worked for me ... but this chap had the right idea / solution 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
回答4:
could be achieved as shown below, and you could also remove trailing 00 at the end if there is no decimals
costing= () => {
const cost= 1478.90 + 940;
return parseFloat(cost).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
}
来源:https://stackoverflow.com/questions/55556221/how-do-you-format-a-number-to-currency-when-using-react-native-expo