Why is a round-trip conversion via a string not safe for a double?

Recently I have had to serialize a double into text, and then get it back. The value seems to not be equivalent: double d1 = 0.84551240822557006; string s = d1.ToString(“R”); double d2 = double.Parse(s); bool s1 = d1 == d2; // -> s1 is False But according to MSDN: Standard Numeric Format Strings, the “R” … Read more

Compare double to zero using epsilon

Today, I was looking through some C++ code (written by somebody else) and found this section: double someValue = … if (someValue < std::numeric_limits<double>::epsilon() && someValue > -std::numeric_limits<double>::epsilon()) { someValue = 0.0; } I’m trying to figure out whether this even makes sense. The documentation for epsilon() says: The function returns the difference between 1 … Read more

How do I parse a string with a decimal point to a double?

I want to parse a string like “3.5” to a double. However, double.Parse(“3.5”) yields 35 and double.Parse(“3.5”, System.Globalization.NumberStyles.AllowDecimalPoint) throws a FormatException. Now my computer’s locale is set to German, wherein a comma is used as decimal separator. It might have to do something with that and double.Parse() expecting “3,5” as input, but I’m not sure. … Read more