Sunday, June 2, 2024
163
rated 0 times [  169] [ 6]  / answers: 1 / hits: 10402  / 4 Years ago, tue, october 13, 2020, 12:00:00

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.


More From » number-formatting

 Answers
3

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 trauncateFractionAndFormat = (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(trauncateFractionAndFormat(formatter.formatToParts(0.99999), 4));
console.log(trauncateFractionAndFormat(formatter.formatToParts(0.006393555), 4));
console.log(trauncateFractionAndFormat(formatter.formatToParts(0.9972620384752073), 4));
console.log(trauncateFractionAndFormat(formatter.formatToParts(12345.67), 4));
console.log(trauncateFractionAndFormat(formatter.formatToParts(20001), 4));




[#2500] Thursday, October 8, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
carlton

Total Points: 373
Total Questions: 123
Total Answers: 97

Location: Saint Helena
Member since Wed, Nov 9, 2022
2 Years ago
carlton questions
Sun, Apr 25, 21, 00:00, 3 Years ago
Wed, Feb 17, 21, 00:00, 3 Years ago
Tue, Oct 27, 20, 00:00, 4 Years ago
Mon, Apr 13, 20, 00:00, 4 Years ago
;