Why does Math.Round(2.5) return 2 instead of 3?

前端 未结 15 1772
灰色年华
灰色年华 2020-11-22 03:54

In C#, the result of Math.Round(2.5) is 2.

It is supposed to be 3, isn\'t it? Why is it 2 instead in C#?

相关标签:
15条回答
  • 2020-11-22 04:39

    Simple way is:

    Math.Ceiling(decimal.Parse(yourNumber + ""));
    
    0 讨论(0)
  • 2020-11-22 04:41

    using a custom rounding

    public int Round(double value)
    {
        double decimalpoints = Math.Abs(value - Math.Floor(value));
        if (decimalpoints > 0.5)
            return (int)Math.Round(value);
        else
            return (int)Math.Floor(value);
    }
    
    0 讨论(0)
  • 2020-11-22 04:42

    The default MidpointRounding.ToEven, or Bankers' rounding (2.5 become 2, 4.5 becomes 4 and so on) has stung me before with writing reports for accounting, so I'll write a few words of what I found out, previously and from looking into it for this post.

    Who are these bankers that are rounding down on even numbers (British bankers perhaps!)?

    From wikipedia

    The origin of the term bankers' rounding remains more obscure. If this rounding method was ever a standard in banking, the evidence has proved extremely difficult to find. To the contrary, section 2 of the European Commission report The Introduction of the Euro and the Rounding of Currency Amounts suggests that there had previously been no standard approach to rounding in banking; and it specifies that "half-way" amounts should be rounded up.

    It seems a very strange way of rounding particularly for banking, unless of course banks use to receive lots of deposits of even amounts. Deposit £2.4m, but we'll call it £2m sir.

    The IEEE Standard 754 dates back to 1985 and gives both ways of rounding, but with banker's as the recommended by the standard. This wikipedia article has a long list of how languages implement rounding (correct me if any of the below are wrong) and most don't use Bankers' but the rounding you're taught at school:

    • C/C++ round() from math.h rounds away from zero (not banker's rounding)
    • Java Math.Round rounds away from zero (it floors the result, adds 0.5, casts to an integer). There's an alternative in BigDecimal
    • Perl uses a similar way to C
    • Javascript is the same as Java's Math.Round.
    0 讨论(0)
提交回复
热议问题