David Božjak
David Božjak

Reputation: 17617

C# Wrong conversion using Convert.ChangeType()

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!

Upvotes: 3

Views: 1622

Answers (3)

Dewfy
Dewfy

Reputation: 23624

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

Upvotes: 2

kitsune
kitsune

Reputation: 11643

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

Upvotes: 4

Adam Robinson
Adam Robinson

Reputation: 185643

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.

Upvotes: 8

Related Questions