Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 57 / 68

Watch Out for Floating-Point Rounding Errors

In this lesson you will learn about floating-point rounding errors in Kotlin, and why decimal arithmetic can produce surprising results. This is for anyone searching for "Kotlin floating point error".

Computers represent decimals in binary, so even a straightforward calculation such as 0.1 + 0.2 may not land exactly on 0.3. Print it and the error is visible; compare it and you get false.

The sample code shows println(0.1 + 0.2) printing a value that includes the error, and the comparison 0.1 + 0.2 == 0.3 coming back false. This happens in most programming languages that use floating-point numbers.

A common stumbling block for beginners is comparing decimals directly with == and not getting the expected answer. Comparing decimals needs an error-aware approach, such as testing whether the difference between the two values is small enough.

In real-world development, where no error is acceptable - monetary calculation, for instance - a higher-precision type such as BigDecimal is recommended.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)