Math.Round vs String.Format

前端 未结 6 1764
天命终不由人
天命终不由人 2021-01-18 18:24

I need double value to be rounded to 2 digits. What is preferrable?

String.Format(\"{0:0.00}\", 123.4567);      // \"123.46\"
Math.Round(123.4567, 2)                 


        
6条回答
  •  Happy的楠姐
    2021-01-18 18:52

    Math.Round(double,digits) with digits>0 is conceptually very unclean. But I think it should never be used. double is a binary floating point number and thus has no well-defined concept of decimal digits.

    I recommend using string.Format, or just ToString("0.00") when you only need to round for decimal display purposes, and decimal.Round if you need to round the actual number(for example using it in further calculations).

    Note: With decimal.Round you can specify a MidpointRounding mode. It's common to want AwayFromZero rounding, not ToEven rounding.

    With ToEven rounding 0.005m gets rounded to 0.00 and 0.015 gets rounded to 0.02. That's not what most people expect.

    Comparisons:

    • ToEven: 3.75 rounds to 3.8
    • ToEven: 3.85 rounds to 3.8 (That's not what most people expect)
    • AwayFromZero: 3.75 rounds to 3.8
    • AwayFromZero: 3.85 rounds to 3.9

    for more information see: https://msdn.microsoft.com/en-us/library/system.math.round.aspx

提交回复
热议问题