Search code examples
javascriptnumber-formatting

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?


Solution

  • 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