Skip to content
Advertisement

How can I convert a JavaScript BigInt value to Scientific Notation?

I would like to render a JavaScript bigint value to a string in scientific notation.

I thought of Number.toExponential() but it only works for numbers.

JavaScript

Advertisement

Answer

Intl does support Bigint:

Turns out BigInt.prototype.toLocaleString() can be used with an options for scientific-notation:

JavaScript

Original answer:

(This code is still useful for JS environments without Intl support or if you need more than 20 digits of precision):

Because bigint values are always integral, and because bigint.toString() will return base-10 digits without further ceremony (other than a leading - for negative values) then then a quick-and-dirty method is to take those rendered digits and insert a radix point (aka decimal dot) after the first digit and tack on the exponent at the end, and because it’s a base-10 string the exponent is the same as the length of the rendered string (neat, huh?)

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement