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
To format a number to currency when using React Native, we can use the react-number-format package. To install it, we run npm i react-number-format . to add the NumberFormat component. value is set to the number to format.
To format a number with commas in React, we can use the number's toLocaleString method. We call toLocaleString on 1234.56789 with { maximumFractionDigits: 2 } to return a number string that has the comma digit separators and the rounded to 2 decimal places. Therefore, we see 1,234.57 displayed.
To format a date string in React Native, we can use moment. js. to call moment with a JavaScript date object to create a moment object with the same date. Then we call format with a format string to return a date string with the given date.
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
You can use this library react-number-format. It has these features
Sample usage
<NumberFormat value={2456981} displayType={'text'} thousandSeparator={true} prefix={'$'} />
Output : $2,456,981
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With