By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,949 Members | 1,169 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,949 IT Pros & Developers. It's quick & easy.

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

P: 2
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
Share this Question
Share on Google+
2 Replies

Expert Mod 2.5K+
P: 2,545
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

P: 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.