Doubles cannot be precise. They are only precise up to a certain number of digits. Remember they use an internal format to be stored in bytes. This will inevitable cause some precision error.
And even worse, some values you put into a double are unable to be precisely stored, even with no calculation made.
Example to make you aware:
Assigning 1.94
to a double
variable can be tested here and will result in:
1.939999999999999946709294817992486059665679931640625
!
Its bad practice and doomed to fail to compare two floating point numbers with equality operator.
Important read about floating point numbers: What Every Computer Scientist Should Know About Floating-Point Arithmetic
Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.
As solution if you really want to compare you can sensitively round the results with Math.round(x, decimals)
before comparing them.