سؤال

I'm running the following javascript code:

var var1 = 0.53;
var var2 = 0.47;
alert(var1-var2);

This code return:

0.06000000000000005

But if I execute this javascript code:

var var1 = 0.14;
var var2 = 100;
alert(var1*var2);

The return is:

14.0600000000000002

What documentation to explain this?

Thanks!

هل كانت مفيدة؟

المحلول

This is a very fundamental problem that is related to the way floating point numbers are represented (see the wikipedia article for a detailed explanation). It is not specific to javascript.

Since a computer works only on binary values it is not possible to exactly represent certain fractions. Example: 1/2 or 3/4 can be exactly represented. 1/3 on the other hand cannot (like in the decimal system). It is counterintutive that a seemingly "simple" number like 0.14 leads to a rounding error, however, when you think about it as 7/50 = 7/(5 * 5 * 2) it becomes clear. The problem are the fives. 1/5 = 0.2 is nice in the decimal system but not as a binary number.

Update:

I don't mean to say it is not possible to do such kinds of calculations exactly. However, you will have to use certain libraries for this purpose (e.g. for working with currency values)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top