A currency-aware way to set minimumFractionDigits
See original GitHub issueWhen displaying currencies in our app, we more or less always want to show 2 decimal points, for cents on all numbers. We can do this with formatNumber by modifying the minimumFractionDigits
attribute. This works well, but there are certain currencies that we don’t want decimal points on. Namely, currencies whose base unit is also its smallest unit, like the Yen (and about 13 other currencies).
I actually think this might be a bad “feature” to add to the helper, but maybe some good advice/documentation on how to achieve this would be helpful to others.
My gut says there’s a way to “reopen” the helper somewhere in my app, and force defaults for minimumFractionDigits
if they aren’t explicitly set. Then I can do the work to know when to set and what to set those defaults to.
Make sense? Can you think of any pretty way to do this?
Here’s my relevant code from my programmatic wrapper of NumberFormat, just to give perspective on what I’m doing.
// some setup
const non100UnitDenominators = {
bif: 1, // Burundian Franc
clp: 1, // Chilean Peso
djf: 1, // Djiboutian Franc
gnf: 1, // Guinean Franc
jpy: 1, // Japanese Yen
kmf: 1, // Comorian Franc
krw: 1, // South Korean Won
mga: 1, // Malagasy Ariary
pyg: 1, // Paraguayan Guaraní
rwf: 1, // Rwandan Franc
vnd: 1, // Vietnamese Đồng
vuv: 1, // Vanuatu Vatu
xaf: 1, // Central African Cfa Franc
xof: 1, // West African Cfa Franc
xpf: 1, // Cfp Franc
};
function getUnitDenominator(currency) {
currency = currency.toLowerCase();
return non100UnitDenominators[currency] || 100;
}
And in the actual file.
if (options.style === 'currency') {
// If we have a 'common' currency, which comes in 'cents', force 2 decimal points
if (getUnitDenominator(options.currency) === 100) {
if (typeof options.minimumFractionDigits === 'undefined') {
options.minimumFractionDigits = 2;
}
if (typeof options.maximumFractionDigits === 'undefined') {
options.maximumFractionDigits = 2;
}
}
}
Would love your opinions!
Issue Analytics
- State:
- Created 9 years ago
- Comments:17 (5 by maintainers)
Top GitHub Comments
Since it was mentioned before I tested rounding having
maximumFractionDigits
set and result was as expected - at least in Internet Explorer 11, Chrome and Firefox.I did not test Safari or any mobile browsers behaviour yet. So can’t say if it’s only Chrome and related browsers which behave strange.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.