const currencyFormatter =( value,format, currency, minimumFractionDigit) => {
console.log(minimumFractionDigit)
const formatter = new Intl.NumberFormat(format || 'en-US', {
style: 'currency',
currency: currency || 'USD',
minimumFractionDigits:minimumFractionDigit ? minimumFractionDigit :2,
});
return isFinite(value) ? formatter.format(value) : '';
};
console.log( currencyFormatter(Math.round(1234.89),undefined,undefined,0)) ;
So the issue I'm facing is that function is receiving the value 0 for the minimumFractionDigit
but the function always returns a value with two decimal points. When I replace minimumFractionDigits
with 0 it returns the desired output. What could be the problem here?
I want to return a value without decimal points from this function.
CodePudding user response:
The problem is you're using the ternary operator to evaluate minimumFractionDigit
. It evaluates the minimumFractionDigit
and if it's falsy, it will use the number 2.
0 evaluates as a falsy value.
Change it to this:
minimumFractionDigits: minimumFractionDigit ?? 2
CodePudding user response:
Change your code like this
Set default value of minimumFractionDigit = 2
The problem was, in javascript if value === 0 then it identified as false
const currencyFormatter = (value, format, currency, minimumFractionDigit = 2) => {
console.log(minimumFractionDigit);
const formatter = new Intl.NumberFormat(format || "en-US", {
style: "currency",
currency: currency || "USD",
minimumFractionDigits: minimumFractionDigit,
});
return isFinite(value) ? formatter.format(value) : "";
};
console.log(currencyFormatter(Math.round(1234.89), undefined, undefined, 0));
Or there is another way
const currencyFormatter = (value, format, currency, minimumFractionDigit) => {
console.log(minimumFractionDigit);
const formatter = new Intl.NumberFormat(format || "en-US", {
style: "currency",
currency: currency || "USD",
minimumFractionDigits: minimumFractionDigit !== undefined ? minimumFractionDigit: 2,
});
return isFinite(value) ? formatter.format(value) : "";
};
console.log(currencyFormatter(Math.round(1234.89), undefined, undefined, 0));