Search code examples
javascriptlocale

Number.prototype.toLocaleString('en-US') strips ten-thousandth decimal place?


In Chrome, if you convert a number to a locale string, it chops off decimal places after the thousandth decimal place:

(10.001).toLocaleString('en-US'); // => '10.001'
(10.0001).toLocaleString('en-US'); // => '10'

Primary question: How do I guard against this?

Tangential questions:

  1. Is this a bug?
  2. Is there a reason I should let it chop off the decimal place?

Solution

  • No, it's not a bug. By default, toLocaleString includes a maximum of 3 fractional digits. You can include more by specifying an options argument with a larger maximumFractionDigits value:

    (10.0001).toLocaleString('en-US', {maximumFractionDigits:20}); // => '10.0001'
    

    From MDN:

    minimumFractionDigits

    The minimum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number and percent formatting is 0.

    maximumFractionDigits

    The maximum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number formatting is the larger of minimumFractionDigits and 3.