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
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
Let's go to the double type:
Console.WriteLine(0.00099d.ToString() == "0.00099"); //false
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
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
Next we compare strings:
Console.WriteLine(0.0d.ToString(CultureInfo.InvariantCulture) == "0.0"); //false
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
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.
Top comments (1)
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
, anddouble
), it might be worth checking a range rather than a direct comparison (for the reasons listed in the article). Instead ofanother approach would be