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
(For example, to decrease the exponent by 3, subtract 3 from the exponent and move the decimal point in the mantissa three times to the right). 2. When all numbers in scientific notation have powers with the same exponent, add or subtract the mantissa(s). Keep the power the same.
How do you cut a number in JavaScript? In JavaScript, trunc() is a function that is used to return the integer portion of a number. It truncates the number and removes all fractional digits.
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.
Description. Floating-point values can be represented using e-notation. E-notation indicates a number that should be multiplied by 10 raised to a given power. The format of e-notation in Javascript is to have a number, integer or floating-point, followed by e or E , than by the power of 10 to multiply by.
You can use the toPrecision
method:
var a = 15 * 1e-9;
a.toPrecision(2); // "1.5e-8"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With