views:

391

answers:

3

Hello!

I am using Convert.ChangeType() to convert from Object (which I get from DataBase) to a generic type T. The code looks like this:

T element = (T)Convert.ChangeType(obj, typeof(T));
return element;

and this works great most of the time, however I have discovered that if I try to cast something as simple as return of the following sql query

select 3.2

the above code (T being double) wont return 3.2, but 3.2000000000000002. I can't realise why this is happening, or how to fix it. Please help!

+7  A: 

What you're seeing is an artifact of the way floating-point numbers are represented in memory. There's quite a bit of information available on exactly why this is, but this paper is a good one. This phenomenon is why you can end up with seemingly anomalous behavior. A double or single should never be displayed to the user unformatted, and you should avoid equality comparisons like the plague.

If you need numbers that are accurate to a greater level of precision (ie, representing currency values), then use decimal.

Adam Robinson
+4  A: 

This probably is because of floating point arithmetic. You probably should use decimal instead of double.

kitsune
+2  A: 

It is not a problem of Convert. Internally double type represent as infinite fraction of 2 of real number, that is why you got such result. Depending of your purpose use:

  • Either Decimal
  • Or use precise formating {0:F2}
  • Use Math.Flor/Math.Ceil
Dewfy