0

I have a string which comes from database. For example it is 5.1 . I want to convert this string to double with double.tryparse() method. I expect the result will be 5.1, but it is not. The result seems like 5.0999999999999996. What can I do to achieve this so that it will be 5.1?

user3894737
  • 31
  • 1
  • 1
  • 10
  • 1
    Whis is it a `varchar` in database and not a `float`/`decimal`? Or are you using code like `row["ColumnName"].ToString()` instead of `row.Field("ColumnName")`? – Tim Schmelter Mar 26 '15 at 09:02
  • 2
    The value 5.1 cannot be represented exactly in type `double`. Why are you using `double` instead of `decimal`? –  Mar 26 '15 at 09:02
  • try to convert as decimal, more precise – cdie Mar 26 '15 at 09:02
  • 3
    You should read about IEEE floats, and how they work: http://en.wikipedia.org/wiki/IEEE_floating_point – Binkan Salaryman Mar 26 '15 at 09:05
  • 2
    **1.** Note re: terminology in your question's title: `double.TryParse` does not *show* anything. It merely converts one value into another. Chances are that you are looking at that method's return value either via `Console.WriteLine`, `MessageBox.Show`, or Visual Studio's Watch / Auto / Locals window. – stakx - no longer contributing Mar 26 '15 at 09:12

1 Answers1

0

Instead of double, do :

decimal.TryParse(s, out myDecimal);

or

 decimal d = Convert.ToDecimal(s);

Because decimal is floating decimal point instead of floating binary. Here's a great explanation : Difference between double and decimal

Community
  • 1
  • 1
cdie
  • 4,014
  • 4
  • 34
  • 57