1

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?

dGayand
  • 599
  • 1
  • 7
  • 15
  • You can do : convert it to string, split with dot, padright with 0 decimal part and concat them. – Eldar Jul 21 '20 at 12:40
  • @Eldar I have tried it, there is an issue when converting small numbers to string as it gives the scientific notation like "9e-8". I have explained it in my post, please read – dGayand Jul 21 '20 at 12:43
  • You've got the proper approach, you've just forgotten that JavaScript uses IEEE floating point numbers. – Heretic Monkey Jul 21 '20 at 12:44
  • Does this answer your question? [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) – Heretic Monkey Jul 21 '20 at 12:45

1 Answers1

2

Number.prototype.toLocaleString will do the trick

    num.toLocaleString('en-US', {minimumFractionDigits: 8, useGrouping: false})//"999999999.90000000"
dkuznietsov
  • 298
  • 1
  • 9