I don’t need to run your example code to see that it would not produce a correct result. It adds up 10⁸ numbers up to 10⁶ each with 2 digits after the decimal point. The intermediate result in the middle of the loop is going to be on the order order 10¹⁴ with two digits after the decimal point. This requires 16 decimal digits of precision to compute correctly, while double-precision floating point has only 15.

The point of this story was not that using floating point for decimal arithemtics is easy. The point is that it is possible, if you keep in mind all the constraints.

Written by

Project Lead for the Kotlin Programming Language @JetBrains

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store