ffonz ffonz -4 years ago 87
C# Question

Why does double.TryParse() return true when the precision > 16

With a small test I use the following code:

double number;
var value = "123456789.123456789";
var style = NumberStyles.AllowDecimalPoint;
var culture = CultureInfo.InvariantCulture;
if (Double.TryParse(value, style, culture, out number))
Debug.WriteLine("Converted '{0}' to {1}.", value, number);
else
Debug.WriteLine("Unable to convert '{0}'.", value);


The result is


Converted '123456789.123456789' to 123456789.123457.


This is because
value
is too long to fit into a double. Only 16 digits are alowed. But shouldn't TryParse() return
false
since information is lost?

Answer Source

Msdn documentation already underlines this fact

However, because of a loss of precision, the values may not be equal

and it does not constitute a conversion failure, that happens instead

if the s parameter is null or String.Empty, is not in a format compliant with style, represents a number less than MinValue or greater than MaxValue, or if style is not a valid combination of NumberStyles enumerated constants.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download