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
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,');
}
Edit: Sorry -this is a React.js solution - not React Native. 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
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
The fastest way is to use react-number-format, as stated above, but don't forget the renderText
prop so that React Native don't throw rendering error.
Follow this step:
npm i react-number-format
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!
/>
);
}
It's working good. As you can see, I ended up creating my custom component that accept value
as prop so I can use it everywhere I need it. Just like this:
<View>
<ReactNativeNumberFormat value={530000} />
</View>
Hope can be useful.
PS: This is my reference => https://github.com/s-yadav/react-number-format/issues/17#issuecomment-395187806.
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