468,117 Members | 1,848 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,117 developers. It's quick & easy.

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);

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.

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

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

5 posts views Thread by sinister | last post: by
12 posts views Thread by Joshua Beall | last post: by
4 posts views Thread by rainmaker1234 | last post: by
2 posts views Thread by Diarmaid McGleenan | last post: by
1 post views Thread by Christine | last post: by
7 posts views Thread by Tor Aadnevik | last post: by
5 posts views Thread by SMichal | last post: by
3 posts views Thread by sparks | last post: by
10 posts views Thread by didacticone | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.