Why Is ToString() Rounding My Double Value?

前端 未结 5 967
别那么骄傲
别那么骄傲 2020-12-03 17:17

How do I prevent my double value from being rounded when converting to a string? I have tried both Convert.ToString and ToString() with the same r

5条回答
  •  醉话见心
    2020-12-03 17:54

    I would assume that the main answer for rounding away the last two digits, is to hide numerical instability/rounding due to float/double finite precision.

    Example with no rounding:

    (Math.Sqrt(7)).ToString("G17") = "2.6457513110645907"
    
    (Math.Sqrt(7)+6).ToString("G17") = "8.6457513110645898"
    

    Looks a bit strange in the last 3 digits, right?

    Example with rounding:

    (Math.Sqrt(7)).ToString() = "2.64575131106459"
    
    (Math.Sqrt(7)+6).ToString() = "8.64575131106459"
    

    Look "perfect", right?

    :-)

提交回复
热议问题