Home >Backend Development >C++ >Why Doesn't `x == 0.1` Work with `double x = 0.1` in C#?

Why Doesn't `x == 0.1` Work with `double x = 0.1` in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-22 20:51:13640browse

Why Doesn't `x == 0.1` Work with `double x = 0.1` in C#?

Floating Point Number Comparison in C#: Decimal Dilemma

In C#, you may encounter some problems when comparing values ​​of type double. Consider the following code:

<code class="language-csharp">double x = 0.1;
if (x == 0.1)
{
    // ...
}</code>

Surprisingly, this code does not enter the if statement. Why is this?

Floating point number problem

The root of the problem lies in the way computers represent floating point numbers (specifically double). Unlike integers, double uses binary fractions instead of decimal fractions. This means that some decimal values, such as 0.1, cannot be stored exactly.

For example, in binary notation, 0.1 is represented as 0.000110011001100110011001.... The computer truncates this infinite loop of decimals into a finite representation, which may not exactly match the expected value.

Solution

In order to solve this problem, you can consider the following methods:

  • Using the decimal type: The decimal type stores numbers using decimal notation, allowing for precise representation.
  • Epsilon comparison: Use a small error margin (e.g. Math.Abs(x - 0.1)) to compare floating point numbers.

Explanation of reasons

Binary fractions differ from decimal fractions in their ability to represent certain numbers. For example, the number 1/10 cannot be represented exactly in binary, resulting in its binary expansion being approximately 0.0001100... The computer's rounding process introduces inaccuracies when storing floating point numbers.

The above is the detailed content of Why Doesn't `x == 0.1` Work with `double x = 0.1` in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn