非对称算术舍入






2.36/5 (8投票s)
2004年10月29日

46092

1
.NET 使用银行家舍入法。想恢复小学时教你的那种舍入方式吗?这段简单的代码可以帮助你!
引言
.NET 舍入仅限于银行家舍入法。我到处搜索替代方案,但没有找到。可能还有更好的方法,但我认为这种方法非常轻量级和简单。
要点:1 - 4:向下舍入,5 - 9:向上舍入。只需将这些函数添加到类、窗体或任何你正在编写的程序中,并在需要进行舍入时调用它们即可。
public static float aaRounding(float numToRound, int numOfDec)
{
return (float)aaRounding((decimal)numToRound, numOfDec);
}
public static double aaRounding(double numToRound, int numOfDec)
{
return (double)aaRounding((decimal)numToRound, numOfDec);
}
public static decimal aaRounding(decimal numToRound, int numOfDec)
{
if (numOfDec < 0)
{
throw new ArgumentException("BetterMath.Rounding:" +
" Number of decimal places must be 0 or greater",
"numOfDec");
}
decimal num = numToRound;
//Shift the decimal to the right the number
//of digits they want to round to
for (int i = 1; i <= numOfDec; i++)
{
num *= 10;
}
//Add/Subtract .5 to TRY to increase the number
//that is to the LEFT of the decimal
if (num < 0)
{
num -= .5M;
}
else
{
num += .5M;
}
//Cut off the decimal, you have your answer!
num = (decimal)((int)num);
//Shift the decimal back into its proper position
for (int i = 1; i <= numOfDec; i++)
{
num /= 10;
}
return num;
}