How small can a JavaScript number be without displaying in scientific notation?

1.8k views Asked by At

I've made some code that rounds off a number to a given number of decimal places but will use more places when there is underflow to avoid rounding just to zero, which wouldn't be informative enough for the user.

But I've noticed that occasionally a small number is displayed in scientific notation. My target users are not expected to be comfortable with scientific notation and in any case such numbers are too small even after handling the underflow and should be treated as zero.

How can I know when a number is so small that it would display in scientific notation?

Is there a smallest number I can compare to and if so what is it? Or is there a better way?

(I know I can convert the number to a string and check if it has an "e" but I'm the type who is curious to know of any math-only solution too.)

1

There are 1 answers

0
Infuzion On BEST ANSWER

There are a few reasons the number is displayed in scientific notation:

  • If the length of significant digits in the number is greater than 21.
  • If the number of zeros before a nonzero number is greater than 6. (e.g. 0.00000001)

The conversion to scientific notation in numbers is specified in Section 9.8.1 of ECMA-262.

An implementation of this specification can be found in the V8 engine here.