Skip to content Skip to sidebar Skip to footer

Simple Subtraction Bug In Javascript

I was shocked to see such a basic subtraction bug in JS, I am sure most of you here would have experienced this issue, please help me with a work around here, All I am doing is su

Solution 1:

Floating point values are never accurate as you expect. You can use Number object to convert this to answer as you need.

Number(100).toFixed(2) - Number(99.1).toFixed(2)

Solution 2:

You are working with floating point numbers, not integers. This is expected.

The reason is that you can't accurately represent numbers like 0.1 and 0.3 in binary. Just like you can't represent 1/3 accruately in decimal form.

Solution 3:

In JavaScript, all of the numeric types are Number objects, which are represented as double-precision floating point numbers.

On another note, you can retrieve a string representation of these numbers to a specific decimal point by using Number's toFixed method, which accepts a number denoting how many decimal points you would like the returned string to represent based on the receiver.

An example:

var five = 5.00001;
console.log(five.toFixed(1)); //5.0

Solution 4:

This is how floating point numbers work, they are not exact. http://en.wikipedia.org/wiki/Floating_point might be useful reading.

Solution 5:

At first prevent yourself from assigning the float value to variable then do it with direct expression to a variable. here is an example:

**var c = 80.35-20.35;
alert(c.toFixed(2));**

this will assign a 60.00 but other way to solve this will return 59.99999999.

Post a Comment for "Simple Subtraction Bug In Javascript"