Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 57 / 68

Watch Out for Floating-Point Rounding Errors

In this lesson you will learn about floating-point rounding errors in C#, and why decimal arithmetic can produce surprising results. This is for anyone searching for "C# floating point rounding 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 Console.WriteLine(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. Knowing that this comes from the IEEE 754 international standard helps the cause make sense.

In real-world development, when this error matters - for monetary calculations, for instance - you need measures such as using the decimal type.

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

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