开发者

round function in c #

开发者 https://www.devze.com 2023-04-11 09:30 出处:网络
public static decimal Round( decimal d, int decimals ) The decimals parameter specifies the number of fractional digits in the return value and ranges from 0 to 28. If decimals is zero, an integer i
   public static decimal Round(
decimal d,
int decimals
    )

The decimals parameter specifies the number of fractional digits in the return value and ranges from 0 to 28. If decimals is zero, an integer is returned.

If the value of the first digit in d to the right of the decimals decimal position is 5, the digit in the decimals position is rounded up if it is odd, or left unchanged if it is even. If the precision of d is less than decim开发者_如何学Pythonals, d is returned unchanged.

    Math.Round(3.44, 1); //Returns 3.4.
   Math.Round(3.45, 1); //Returns 3.4.

Why 3.45 is returning 3.4..I am unable to understand this output.Can anyone help


You can change this behaviour by using the Round overload which take the MidpointRounding parameter, from MSDN:

ToEven (default, AKA Bankers Rounding) When a number is halfway between two others, it is rounded toward the nearest even number.
AwayFromZero When a number is halfway between two others, it is rounded toward the nearest number that is away from zero.


Like you said,

If the value of the first digit in d to the right of the decimals decimal position is 5, the digit in the decimals position is rounded up if it is odd, or left unchanged if it is even.

With 3.45, the first digit to the right of the decimal is 5, and since 4 is even, it's left unchanged. This is a pretty standard way of rounding, because if 5 is always rounded up, this can weight things like averages and sums higher than they should be.


The default rounding is MidpointRounding.ToEven (banker's rounding) which means it will gravitate towards an even number for the digit at the rounding location (i.e., it will move to 3.4 because 4 is even).

This is intended to minimise the accumulation of errors which may occur when all midpoint rounding goes in the same direction (though this of course depends on your input data - an equal mix of positive and negative numbers may be fine with AwayFromZero).

So you have:

Math.Round(3.44, 1); //Returns 3.4.
Math.Round(3.45, 1); //Returns 3.4 (down towards 4).
Math.Round(3.54, 1); //Returns 3.5.
Math.Round(3.55, 1); //Returns 3.6 (up towards 6).

See this answer for a detailed explanation of all the options available to you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号