简体   繁体   中英

Javascript How to convert a decimal number to a string with specific number of decimal places

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, ie 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM