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?
Asked
Active
Viewed 1,752 times
0
-
1Whis 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 -
2The 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
-
3You 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 Answers
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
-
2Any explanation why his code fails would be really nice to know for the author. – Binkan Salaryman Mar 26 '15 at 09:04
-
-
I am so sorry, I did it accidentally. The solution is worked for me. Thanks a lot. – user3894737 Mar 26 '15 at 09:11
-
@user3894737 You can't "un-downvote", but you can change to an upvote – Binkan Salaryman Mar 26 '15 at 09:12
-
1
-
-