2

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.

Sai Krishna
  • 593
  • 1
  • 8
  • 25
  • `parseFloat` does *not* convert it to scientific notation, it converts it to a *number*. It's `toFixed()` that converts it to a string in scientific notation. – Bergi Jan 21 '22 at 01:52
  • You might be looking for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision instead? – Bergi Jan 21 '22 at 01:57

1 Answers1

1

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

Edit, additional info

Bigint library (or also the builtin data type) can only handle integers. I think try the JavaScript numeric operation library seems to be the fastest way to calculate the decimal point. A bignumber library typically works with arbitrary-precision floating-point numbers. There are several recommended libraries. bignumber.js Or BigNumber

Hyunjune Kim
  • 465
  • 4
  • 12
  • Hey. This does work for large valued integers, but I have some numbers with large float values. How could I handle this? – Sai Krishna Jan 20 '22 at 20:06
  • Yes. bigint library (or also the builtin data type) can only handle integers. I think try the JavaScript numeric operation library seems to be the fastest way. A bignumber library typically works with arbitrary-precision floating-point numbers. There are several recommended libraries. [bignumber.js](https://github.com/MikeMcl/bignumber.js) Or [BigNumber](http://jsfromhell.com/classes/bignumber) – Hyunjune Kim Jan 21 '22 at 01:22