Things are always not how they appear. Especially when it comes to multiplication of decimal numbers in Javascript.
Consider -
|
|
Multiply the above number by 3
. Compare with expected answer just to make sure you are not seeing a wrong answer.
|
|
This happens because Javascript treats all of its numbers as floating point numbers, and their binary math cannot exactly represent numbers which has denominator not divisible by 2.
See this excellent StackOverFlow post for an explanation. And, see this by the author of the selected answer.
Excerpt:
Binary floating point math is like this. In most programming languages, it is based on the IEEE 754 standard. JavaScript uses 64-bit floating point representation, which is the same as Java’s double. The crux of the problem is that numbers are represented in this format as a whole number times a power of two; rational numbers (such as 0.1, which is 1/10) whose denominator is not a power of two cannot be exactly represented.
For 0.1 in the standard binary64 format, the representation can be written exactly as 0.1000000000000000055511151231257827021181583404541015625 in decimal, or 0x1.999999999999ap-4 in C99 hexfloat notation. In contrast, the rational number 0.1, which is 1/10, can be written exactly as 0.1 in decimal, … The sum of 0.1 and 0.2 winds up being larger than the rational number 0.3 and hence disagreeing with the constant in your code.
… For an easier-to-digest explanation (of floating point arithmetic), see [floating-point-gui.de].
All positional (base-N) number systems share this problem with precision. Plain old decimal (base 10) numbers have the same issues, which is why numbers like 1/3 end up as 0.333333333.
The simplest fix is to round-off numbers.
|
|
Another way of addressing this problem is by doing calculations after converting decimals to integers through scaling. For e.g. 3.14 = 314. Now do all calculations with 314.
The scaling method is especially useful if you are doing money-related calculations - convert everything to the lowest denomination and perform calculations.