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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MayuriPaleja
    New Member
    • Jun 2012
    • 2

    #1

    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.ToSin gle(a);
    Response.Write( r);

    Why I am getting this greater value.
  • Stewart Ross
    Recognized Expert Moderator Specialist
    • Feb 2008
    • 2545

    #2
    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
    Last edited by Stewart Ross; Jun 30 '12, 05:29 PM.

    Comment

    • MayuriPaleja
      New Member
      • Jun 2012
      • 2

      #3
      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.

      Comment

      Working...