Search code examples
javascriptnumber-formatting

Javascript "toLocaleString()" function chnages decimals to zero when number is very large


I am developing a react app and i need to format some numbers using toLocaleString function and i realize that the decimal part of the number changes to zero when the number is very

(10000.25).toLocaleString('en',{maximumFractionDigits: 2, minimumFractionDigits: 2});
//Output: 10,000.25

(10000000000000000000.25).toLocaleString('en',{maximumFractionDigits: 2, minimumFractionDigits: 2});
//Output: 10,000,000,000,000,000,000.00

why is this so? is it a bug or am I missing something?


Solution

  • Javascript compiler cannot handle very large numbers. Use Number.MAX_SAFE_INTEGER to check the last number it can handle. Try to consider using string type from the beginning if these numbers are not calculated (Maybe if you get it from an API kind of), or try using BigInt type.

    For floating point, the maximum number it can handle to a precision of 1 decimal digit is 562949953421311 and it differs for other digits. This has been referred here. Try using the BigNumber class in your case.