简体   繁体   中英

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!

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM