Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# float to decimal conversion

Any smart way to convert a float like this:

float f = 711989.98f;

into a decimal (or double) without losing precision?

I've tried:

decimal d = (decimal)f;
decimal d1 = (decimal)(Math.Round(f,2));
decimal d2 = Convert.ToDecimal(f);
like image 502
Adrian4B Avatar asked Apr 07 '10 18:04

Adrian4B


4 Answers

It's too late, the 8th digit was lost in the compiler. The float type can store only 7 significant digits. You'll have to rewrite the code, assigning to double or decimal will of course solve the problem.

like image 190
Hans Passant Avatar answered Sep 18 '22 14:09

Hans Passant


This may be a compiler bug because it seems like a valid float should convert directly to a decimal. but it wont without losing resolution. Converting 125.609375 from float to decimal will lose resolution. However, converting it from float to double and then double to decimal will keep resolution.

    float float_val = 125.609375f;

    decimal bad_decimal_val = (decimal)float_val;   //125.6094

    double double_val = (double)float_val;
    decimal good_decimal_val = (decimal)double_val;
like image 26
John Avatar answered Sep 20 '22 14:09

John


have you tried?

decimal.TryParse()

http://forums.asp.net/t/1161880.aspx

There are no implicit conversions between float/double and decimal. Implicit numeric conversions are always guaranteed to be without loss of precision or magnitude and will not cause an exception.

like image 27
hunter Avatar answered Sep 21 '22 14:09

hunter


You lost precision the moment you've written 711989.98f.

711989.98 is decimal. With f in the end you are asking the compiler to convert it to float. This conversion cannot be done without losing precision.

What you probably want is decimal d = 711989.98m. This will not lose precision.

like image 43
mfeingold Avatar answered Sep 19 '22 14:09

mfeingold