简体   繁体   中英

Javascript: prevent parseFloat from converting large number to scientific notation

I have some data in a node app which are numbers in string format. I'm trying to parse them and round off to 3 decimals by parseFloat(num).toFixed(3) . Since the numbers are very large, it is automatically converting them to scientific notation (eg 2.0210702881736412e+37). I switched to using parseInt(), Number() but nothing works. How do I get around this?

The data object is very huge so I'm skeptical to use a custom converter function which converts the exponential form to decimal, since it might impact performance.

Use BigInt

const num = BigInt(2.0210702881736412e+37);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt

BigInt values are similar to Number values in some ways, but also differ in a few key matters: A BigInt value cannot be used with methods in the built-in Math object and cannot be mixed with a Number value in operations; they must be coerced to the same type. Be careful coercing values back and forth, however, as the precision of a BigInt value may be lost when it is coerced to a Number value.

How you use BigInt for it: BigInt(n).toString();

const num = BigInt(2.0210702881736412e+37);
// 20210702881736411847466551731631947776n

const strNum = num.toString();
// 20210702881736411847466551731631947776

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