Why does .Net use a rounding algorithm in String.Format that is inconsistent with the default Math.Round() algorithm?

前端 未结 4 915
夕颜
夕颜 2020-12-29 21:20

I\'ve noticed the following inconsistency in C#/.NET. I was wondering why it is so.

Console.WriteLine(\"{0,-4:#.0} | {1,-4:#.0}\", 1.04, Math.Round(1.04, 1)         


        
4条回答
  •  孤城傲影
    2020-12-29 21:46

    Please, take a look here: Possible Bug: Math.Round returning inconsistent results

    WriteLine() simply calls Object.ToString(), which in turn ultimately results in a call to Number.FormatDouble(this, null, NumberFormatInfo.CurrentInfo). As you can see, the parameter for the format string is null. If you want to get the real thing from ToString() you must use System.Diagnostics.Debug.WriteLine(n.ToString("R")).

    "When a Single or Double value is formatted using this specifier, it is first tested using the general format, with 15 digits of precision for a Double and 7 digits of precision for a Single. If the value is successfully parsed back to the same numeric value, it is formatted using the general format specifier. If the value is not successfully parsed back to the same numeric value, it is formatted using 17 digits of precision for a Double and 9 digits of precision for a Single." Standard Numeric Format Strings

提交回复
热议问题