Is there a way to truncate scientific notation numbers in Javascript?

As you all know, since this is one of the most discussed topics in SO, I am having problems with rounding errors (in fact, these are not errors, I am well aware). Instead of clarifying my point of view, I will give an example of what possible numbers I have and what input I want to get:

Let's say

var a = 15 * 1e-9;
alert(a)

exits

1.5000000000000002e-8

I want to get 1.5e-8instead, but I can’t just multiply by 10e8, round and divide by 10e8, because I don’t know if it will be e-8 or e-45 or anything else.

So basically I want to get a part 1.5000002, apply toFixed(3)and return a part of the exponent.

I could convert to string and parsing, but that just doesn't seem right ...

Any idea?


( , , , , )

+3
2

toPrecision:

var a = 15 * 1e-9;
a.toPrecision(2); // "1.5e-8"
+8

:

0

Source: https://habr.com/ru/post/1788542/


All Articles