Skip to content Skip to sidebar Skip to footer

Javascript Float Subtract

I was wondering how can I subtract two negative Floating-Point numbers in javascript. I tried: alert(-0.2-0.1); and the result is -0.30000000000000004. Am I doing something wrong?

Solution 1:

No, nothing wrong with your code, most decimal fractions cannot be represented exactly in binary, use

number.toFixed(x)

Where x is the number of decimals you want and number is the result of the subtraction.

Solution 2:

Another possible solution might be this:

Number((-0.2-0.1).toFixed(x))

Where x should be the tolerance in decimals you'd like.

Running this with an x of 16, gives me an output of -0.3.

-0.3 === Number((-0.2-0.1).toFixed(16)) // true, and also with every 0 < x < 16

Let me know.

Solution 3:

You are doing nothing wrong, what you are seeing is the side effect of computers storing numbers in base 2. In base 10, 1/3 can't be precisely represented: .33333333 (with a bar over the 3). The same is true for 1/10 and 1/5 in base 2 or binary. The answer you see is merely the result of a rounding error. If you are working with money, it is often advised to just store values as cents to avoid some floating point errors.

As far as fixing the result you can do something like:

varSIGDIG= 100000000;
alert( Math.floor((-0.2-0.1)*SIGDIG)/SIGDIG );

Solution 4:

The reason of your problem is explained here: Why does modulus operator return fractional number in javascript?

A possible solution could be:

<scripttype="text/javascript">var result = (-20-10)/100;
alert("My result is "+result);
</script>

Solution 5:

toFixed() is what you must be looking for.

E.g

number.toFixed(x); 

where x is the number of digits after the decimal point. It is optional with default value of 0.

More here : Javascript Number.toFixed() Method

Post a Comment for "Javascript Float Subtract"