简体   繁体   中英

how to convert a number to float with 8 point decimal places in javascript

How can i convert a number, a input from my test case which will be of either integer or float, into a float/string number of always with 8 decimal places? say for example, if my input is 3, then i should convert into '3.00000000', if my input is 53.678, then i should convert into '53.67800000'. I have googled and tried with few conversion types like parsing, toPrecision() but could not convert it. Any help is much appreciated.

expect(a).to.equal(b) // a and be should be of same number with types too
expect(a).to.equal(b)

In JavaScript, Number is a double-precision float.
Its precision cannot be expressed in decimal places , it varies depending on how big the number is. Above Number.MAX_SAFE_INTEGER , for example, the precision is "less than 0 decimal places":

 const large = 9007199254740992; const larger = large + 1; console.log(large === larger);

To convert a Number to a String with a fixed number of decimal places, use .toFixed() , as @epascarello suggested:

 const input = 3; const str = input.toFixed(8); console.log(str);

As for doing financial calculations, some say you should never use IEEE 754 floats (such as JavaScript's Number s), although many of the largest companies in finance do just that.
To be on the safe side, use a bignum library such as big.js .

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