DEV Community

Serhii Korol
Serhii Korol

Posted on

Funny numbers in C#.

Today, I would like to discuss numbers in C#. Of course, everyone knows that C# is not JS, but someone can be astonished. And so, let's begin.
Let's start with decimal type:

Console.WriteLine(0.00000m.ToString() == "0.00000"); //false
Enter fullscreen mode Exit fullscreen mode

Why? It's simple. The decimal number was converted to a string with current culture and returned a comma instead dot. This issue resolves the following code below. It would be best if you remembered it.

Console.WriteLine(0.00000m.ToString(CultureInfo.InvariantCulture) == "0.00000"); //true
Enter fullscreen mode Exit fullscreen mode

Let's go to the double type:

Console.WriteLine(0.00099d.ToString() == "0.00099"); //false
Enter fullscreen mode Exit fullscreen mode

Why? The double number isn't equal to 0.00099, and it's similar to 0.00098999999999999999. So this case also needs to be remembered.
Let's consider another example:

Console.WriteLine((-0d).ToString() == "0"); //false
Enter fullscreen mode Exit fullscreen mode

Why? Because the zero can be a negative number, it was converted with a minus. Further, it's more interesting:

Console.WriteLine(-0d == 0d); //true
Enter fullscreen mode Exit fullscreen mode

Next we compare strings:

Console.WriteLine(0.0d.ToString(CultureInfo.InvariantCulture) == "0.0"); //false
Enter fullscreen mode Exit fullscreen mode

In this case, the 0.0d was converted to 0 and then to "0".

And the cherry on the cake. Let's look at another example:

Console.WriteLine((double)0.1f == 0.1); //false
Enter fullscreen mode Exit fullscreen mode

I want to explain what I do. The number 0.1 is double, and I convert float to double, and we get false. Why? Because the 0.1 is actually equal to 0.10000000000000001 and converted 0.1f equal 0.10000000149011612.

Let's make conclusions. Always control numbers with the comma and restrict digits after the comma.

Buy Me A Beer

Top comments (1)

Collapse
 
ant_f_dev profile image
Anthony Fung

Nice overview of number handling!

Be careful with number formats. Some cultures, e.g. UK/US use . for decimal point and , for number groupings; however some cultures, e.g. Europe use , for decimal point and . for number grouping.

Also, for comparing floating point numbers (float, and double), it might be worth checking a range rather than a direct comparison (for the reasons listed in the article). Instead of

if (myDouble == 0)
Enter fullscreen mode Exit fullscreen mode

another approach would be

if (myDouble < 0.001)
Enter fullscreen mode Exit fullscreen mode