I'm using Intl.NumberFormat
to format numbers:
const formatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 1,
maximumFractionDigits: 4,
minimumSignificantDigits: 1,
maximumSignificantDigits: 4
})
formatter.format(0.99999) // results: '1'. desired result: '0.9999'
formatter.format(0.006393555) // results: '0.006394'. desired result: '0.006393'
formatter.format(0.9972620384752073) // results: '0.9973'. desired result: '0.9972'
formatter.format(12345.67) // results: '12,350'. desired result: '12,345.67'
formatter.format(200001) // results: '200,000'. desired result: '200,001'
As you can see the numbers are being rounded automatically, which is undesirable behavior in my case.
Is there a way to tell the formatter not to round? I Didn't found any option or combination of options to achieve that.
I don't think this is possible with current spec and there are few proposals for the new spec, but you can still use formatToParts
method and add custom function to format number parts as you wish.
For your first use case it could look something like:
const truncateFractionAndFormat = (parts, digits) => {
return parts.map(({ type, value }) => {
if (type !== 'fraction' || !value || value.length < digits) {
return value;
}
let retVal = "";
for (let idx = 0, counter = 0; idx < value.length && counter < digits; idx++) {
if (value[idx] !== '0') {
counter++;
}
retVal += value[idx];
}
return retVal;
}).reduce((string, part) => string + part);
};
const formatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 0,
maximumFractionDigits: 20
})
console.log(truncateFractionAndFormat(formatter.formatToParts(0.99999), 4));
console.log(truncateFractionAndFormat(formatter.formatToParts(0.006393555), 4));
console.log(truncateFractionAndFormat(formatter.formatToParts(0.9972620384752073), 4));
console.log(truncateFractionAndFormat(formatter.formatToParts(12345.67), 4));
console.log(truncateFractionAndFormat(formatter.formatToParts(20001), 4));