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

3

6

As you all know since it is one of the most asked topic on SO, I am having problems with rounding errors (it isn't actually errors, I am well aware). Instead of explaining my point, I'll give an example of what possible numbers I have and which input I want to be able to obtain:

Let's say

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

outputs

1.5000000000000002e-8

I want to be able to obtain 1.5e-8 instead, but I cannot 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 be able to obtain the 1.5000002 part, apply toFixed(3) and put back the exponent part.

I could convert into a string and parse but it just doesn't seem right...

Any idea ?


(I apologize in advance if you feel this is one of many duplicates, but I could not find a similar question, only related ones)

Gael

Distract answered 28/1, 2011 at 17:2 Comment(0)
P
13

You can use the toPrecision method:

var a = 15 * 1e-9;
a.toPrecision(2); // "1.5e-8"
Plaided answered 28/1, 2011 at 17:9 Comment(3)
This, as documented, gives you a (typeof a ==) "string"; great for output. If you want to get a "number" back you can do var b = 1 * a.toPrecision(2); Beware of rounding in the middle of a computation.Incitement
@Stephen, yes, or var b = +a.toPrecision(2); or var b = Number(a.toPrecision(2));Phip
Wasn't expecting an easy solution ! I shall look deeper into documentation next time !Distract
C
0

If you're doing scientific work and need to round with significant figures in mind: Rounding to an arbitrary number of significant digits

Coliseum answered 28/1, 2011 at 17:13 Comment(0)
G
-2
var a = 15 * 1e-9;

console.log(Number.parseFloat(a).toExponential(2));

//the above formula will display the result in the console as: "1.50e-8"
Genia answered 30/8, 2022 at 18:0 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Stalkinghorse

© 2022 - 2024 — McMap. All rights reserved.