I have written a currency formatter that takes user inputs and displays it in currency format eg( user inputs 1000, it is supposed to show up as 1,000.00 This is my code below
const Currency = (props) => {
const defaultOptions = {
significantDigits: 2,
thousandsSeparator: ",",
symbol: props.symbol ? props.symbol : "NGN",
};
const amountValue = props.value ? props.value : 0.0;
const formatCurrency = () => {
let localAmount = amountValue;
if (typeof localAmount !== "number") {
localAmount = 0.0;
}
const currency = Math.floor(localAmount).toString();
return `${defaultOptions.symbol} ${currency.replace(
/(d)(?=(d{3})+(?!d))/g,
`$1${defaultOptions.thousandsSeparator}`
)}`;
};
return <Text {...props}>{formatCurrency()}</Text>;
};
However I want to modify it to not display the decimal part, for example when a user enters 12345678, I want to display it as 12,345,678 and not 12,345,678.00
When I try to modify it, the thousand separator no longer works as it should
3
Answers
You could make the browser do all the work for you with
Intl.NumberFormat
. This example uses thestripIfInteger
option to truncate the currency if the minor unit is all zeros.What you did works as expected sample
You can try it
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat