Ad space (banner)
๐ŸนGo Lessons
Lesson 57 / 68

Watch Out for Floating-Point Rounding Errors

In this lesson you will learn about floating-point rounding errors in Go, and why decimal arithmetic can produce surprising results. This is for anyone searching for "Go 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 fmt.Println(0.1 + 0.2) printing 0.30000000000000004, error included, 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. Knowing that this comes from the IEEE 754 international standard helps the cause make sense.

In real-world development, work that demands precision such as monetary calculation needs a measure like calculating in integers (in cents rather than dollars).

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

๐Ÿงช This site can't compile or run Go 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)