Java/Scala: Why you shouldn’t use double or float values for currency alvin January 28, 2019 - 2:31pm

As a brief note, here are a couple of examples about why you shouldn’t use double or float values for currency, courtesy of Joshua Bloch’s Effective Java book:

scala> 1.03 - .42
val res0: Double = 0.6100000000000001

scala> 1.00 - 9 * 0.10
val res1: Double = 0.09999999999999998

Political issues affect clocks

Per this story on ycombinator, it appears that political issues can affect clocks:

The short version of the story is that grid electricity in Europe is produced by rotating the turbines 50 times a second and that's where the 50Hz AC electricity comes from. Apparently to match the demand at given instance electricity plants rotate their turbines a bit faster or a bit slower instead of switching a complete plant on and off, which results in slight deviations from the 50Hz standard but it is fine as long as it stays between the limits.

At the end of the day, as the demand increases and decreases, the average frequency would be 50Hz and engineers took advantage of that fact to create clocks that may not be accurate to the second but accurate on average. How do they do that? They count the change in the electricity and assume that 50 changes are exactly 1 second.

Unfortunately, due to political issues in the Balkans, the grid was under-supplied or over-supplied for a prolonged period and this created a deviation from the average of 50Hz and the clocks that depend on this average to be 50Hz also lost accuracy that currently amounts to 6 minutes.

How to compare floating-point numbers in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 2.5, “Comparing Floating-Point Numbers in Scala.”


You need to compare two floating-point numbers in Scala, but as in some other programming languages, two floating-point numbers that should be equivalent may not be.