unknown
unknown

Reputation: 23

javascript addition and subtraction behaving weird

When I tried to execute this piece of code, its giving me a very weird answer

<script type="text/javascript">
  a = 17.98 + 7.99 - 17.98 - 7.99 + 0 - 0;
  alert(a);
</script>

It should actually give me a zero. But instead it gives me an exponential value. Can some one please help me with the answer.

Upvotes: 1

Views: 393

Answers (4)

user2587132
user2587132

Reputation:

a = Math.ceil(17.98 + 7.99 - 17.98 - 7.99 + 0 - 0);

Upvotes: 0

Rahul K
Rahul K

Reputation: 705

Computers are not really good with handling floating points.

eg: 0.1 + 0.2 = 0.30000000000000004

Because internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all. When the code is compiled or interpreted, your “0.1” is already rounded to the nearest number in that format, which results in a small rounding error even before the calculation happens.

read more on : What Every Programmer Should Know About Floating-Point Arithmetic

Upvotes: 1

Guffa
Guffa

Reputation: 700402

That's normal behaviour for floating point calculations.

There is only a limited number of values that can be represented exactly in the binary floating point format used, so most values are represented as the closest possible value.

A value like 7.99 might be represented as something like 7.98999999999997754, so that's the value that you actually get when the code is parsed.

The difference between the actual value and the value that you expect is so small that it doesn't show up when you just display the value directly, as the value is rounded when it is turned back into a string format. When you do several calculations the small differences add up, and sooner or later you will see it.

The result that you get is -0.0000000000000017763568394002505, so that is very close to zero, but it's not exactly zero.

Upvotes: 1

mdup
mdup

Reputation: 8529

You should get -1.7763568394002505e-15. This represents -1.7763568394002505 * 10^(-15). This is a value very close to zero ; but the fact that you don't get zero is due to a rounding error. This is normal behaviour.

If you really want to know the in and outs, you can find out more at http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

Upvotes: 2

Related Questions