In a javascript code, I have a requirement to format a decimal number to a specific number of decimal places and get its exact string representation. For example, If the number is 999999999.9 and the number of decimal places is 8, then the expected value should be "999999999.90000000"
When the Number.toFixed(8) is used it returns a rounded value which is not what I want. Please refer the below code
var num = 999999999.9
var string_rep = num.toFixed(8)
>> the value of string_rep is "999999999.89999998"
I used num.toString() and tried to manually format the decimal part by adding/removing digits, but it does not work for very small numbers like "0.00000008" as the function toString() returns the scientific notation, i.e. something like "9e-8"
So what should be the proper approach for this?
Number.prototype.toLocaleString
will do the trick
num.toLocaleString('en-US', {minimumFractionDigits: 8, useGrouping: false})//"999999999.90000000"