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

前端 未结 4 943
夕颜
夕颜 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:25

    WriteLine(string, params object[]) calls string.Format and passes in the current CultureInfo, so will use your localized NumberFormatInfo to determine how to write the number. Math.Round does not take culture into account, since you are specifying exactly how you want it to round.

    Hm, after poking around Reflector, maybe not :)

提交回复
热议问题