简体   繁体   中英

Format JavaScript numbers to trim zeroes and have commas

Here's what I need:

121 => 121
14231.439400000 => 14,231.4394
1.123456789 => 1.12345679
-9012.4430001 => -9,012.4430001

I've tried the following: return input.toFixed(8).toLocaleString().replace(/0*$/, '').replace(/\\.$/, '');

and that doesn't add commas. I've also looked at numeraljs , but that doesn't have the decimal features I require (specifying up to 8 decimals out, or trimming)

Any help?

This should work on any browser that supports locales and the options described on MDN :

return input.toLocaleString("en", { 
    useGrouping: true, 
    maximumFractionDigits: 8 
});

Demonstration

And here's an alternative solution adapted from Elias Zamaria 's answer here :

var x = input.toFixed(8).split('.');
return x[0].replace(/\B(?=(\d{3})+(?!\d))/, ',') + 
       ('.' + x[1]).replace(/\.?0+$/, '');

Demonstration

Or if you want to do it yourself:

 function fixNumber(number){ var roundedNumber = Math.round(parseFloat(number) * 100000000) / 100000000, numberString = roundedNumber.toString(), parts = numberString.split('.'), integerPart = parts[0], decimalPart = parts.length > 1 ? parts[1] : ''; integerPart = integerPart.split('').reverse().join('').replace(/(\\d{3})/g, '$1,').split('').reverse().join('').replace(/^(-?),/, '$1'); decimalPart = decimalPart.replace(/0+$/, ''); return decimalPart.length ? integerPart + '.' + decimalPart : integerPart; } document.write(fixNumber(121) + '<br>'); document.write(fixNumber(14231.439400000) + '<br>'); document.write(fixNumber(1.123456789) + '<br>'); document.write(fixNumber(-9012.4430001) + '<br>'); 

JSFiddle

Internationalization Support is now readily available in all browsers and nodejs. The advantage to this is that it's fast and configurable. For example, you can specify a minimum number of decimal precision and a maximum.

// Decimal Style (1,234,56)
let formatter = new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 0, maximumFractionDigits: 8 });
formatter.format(1234.5678); // result: "1,234.57"

// Currency Style ($1,234.56)
let formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 0, maximumFractionDigits: 2 });
formatter.format(28761232.291); // result: "$28,761,232"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM