tags:

views:

250

answers:

3

Any smart way to convert a float like this:

float f = 711989.98f;

into a decimal (or double) without loosing precision?

I've tried:

decimal d = (decimal)f;
decimal d1 = (decimal)(Math.Round(f,2));
decimal d2 = Convert.ToDecimal(f);
+1  A: 

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.

hunter
+1  A: 

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.

Hans Passant
thanksI've changed the type of the field on mapped object from float to decimal and solved the conversion issue that was happening during deserialization.
Adrian4B
A: 

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 loosing precision.

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

mfeingold