Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

round exponentially small number with .toFixed()

How can I round an exponentially small number like this:

2.4451778232910804e-26.toFixed(4) => 2.4452e-26

In docs, using .toFixed() is going to give me every time 0. Is there a special function for exponentially small number? I would rather not modify Number.prototype.toFixed().

like image 252
nehel Avatar asked Sep 16 '16 11:09

nehel


People also ask

Does toFixed round up?

Description. The toFixed() method returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.

What is the toFixed () function used for?

The toFixed() method can be used to convert an exponential number into a string representation with a specific number of digits after the decimal place.

How do I return toFixed as number?

The method toFixed(n) rounds the number to n digits after the point and returns a string representation of the result. We can convert it to a number using the unary plus or a Number() call, e.g write +num. toFixed(5) .

What is difference between toFixed and toPrecision?

toFixed() returns digits before decimal point including digits(as per parameter) after decimal point but toPrecision() returns digits(as per parameter) before decimal and after decimal point. Difference is toFixed() count starts after decimal point but toPrecision() count starts before decimal point.


1 Answers

As you already wrote, toFixed isn't precise enough, as it only allows "only" up to 20 decimal places. Multiply + Dividing won't work as well, as the division might give you an inaccurate longer number again. But toPrecision(<amount-of-precision>) might help.

edit: If you want 4 decimal places, you need pass 5 as parameter (as the numbers before the point count as well).

toPrecision will give you a String, but you may easily cast it back to a number again, if needed. e.g. Number(someNumberAsString)

var someNumber = 2.4451778232910804e-26;
console.log(someNumber);
console.log(someNumber.toPrecision(8));
like image 101
MattDiMu Avatar answered Oct 02 '22 10:10

MattDiMu