c# convert string to single
i have a program r开发者_JAVA技巧unning for a while and everything works fine till this weird thing happens. when i convert a number string to Single, i just can't get the value i want. for example:
Convert.ToSingle("11006.954")
return the value 11006.9541
Convert.ToSingle("20678.228")
return the value 20678.2285
I know i can fix it using Convert.ToDouble but it will take days to modify the existing system. I am using vs2003 .net 1.1.
You seem to be expecting a Single
to be able to represent exactly the numbers you've given. It can't. 11006.9541 is the closest Single
value to 11006.954. (In fact, the exact value of the closest Single
is 11006.9541015625, but I suspect you're seeing 11006.9541 in the debugger.)
If you want accurate representations of numbers originally expressed as decimals, you should use System.Decimal
.
See my articles on binary floating point and decimal floating point in .NET for further information.
精彩评论