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

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

    Seems this problem is worse than a "simple" inconsistency:

    double dd = 0.034999999999999996;
    
    Math.Round(dd, 2); // 0.03
    Math.Round(dd, 2, MidpointRounding.AwayFromZero); // 0.03
    Math.Round(dd, 2, MidpointRounding.ToEven); // 0.03
    
    string.Format("{0:N2}", dd); // "0.04"
    

    This is absolutely bananas. Who knows where the heck it get "0.04" from.

提交回复
热议问题