468,117 Members | 1,848 Online

# Converting A String To Single and the Assigning IT To Double.

I am Converting a string value to single and then to double.
For 1371818.28 i am getting Answer 137181.28125
For 1371818.29 i am getting Answer 137181.296875

Below is the code i am using.

string a="137181.28";
double r=Convert.ToSingle(a);
Response.Write(r);

Why I am getting this greater value.
Jun 30 '12 #1
2 1666
Stewart Ross
2,545 Expert Mod 2GB
You are expecting far too much precision. The single data type can store just seven significant digits (though internally nine are used). The two values you quote, 1371818.28 and 1371818.29, are the same to seven significant digits (1371818), and are only different at the very end of the internally-used range, nine digits.

Please note that you have posted two different versions of the numbers concerned, one with 7 digits before the decimal point (quoted above) and your code with six digits before the point. If your code is correct the same problem is arising - you are using eight significant digits in a type which can only represent seven digits reasonably accurately.

Like all floating-point systems, there are approximations used in representing numbers internally, and as you are using more digits than the type can represent accurately you are getting noticeable rounding errors in the values concerned.

Why would you convert to single first? Why don't you just convert straight to double? Double can represent 15 significant digits, and is subject to far smaller rounding errors than single is.

-Stewart
Jun 30 '12 #2
Thanks Ross,

Yes there is the difference in values in my question and my code.But I think you have got my problem right.

Conversion to 'double ' is the right way but ,this is the exiting code which i am working on ,which was coded by other team and our team is facing a problem due to this.

I actually want to know wht happens internally which causes this rounding problems.Is there any documentation to explain this problem.
Jul 2 '12 #3