以10为底的常规RoundUp函数如下所示:
public static decimal RoundUp(this decimal value, int decimals)
{
var k = (decimal)Math.Pow(10, decimals);
return Math.Ceiling((value * k)) / k;
}
所以它是这样的:
decimal number = 10.12345m;
number.RoundUp(3) => 10.124
number.RoundUp(2) => 10.13
number.RoundUp(1) => 10.2
etc.
我想具有一个舍入为最接近值的函数,如下所示:
decimal number = 10.12345m;
number.RoundUp(0.1) => 10.2
number.RoundUp(0.25) => 10.25
number.RoundUp(2.0) => 12
number.RoundUp(5.0) => 15
number.RoundUp(10) => 20
请注意,基于整数的取整意味着我们得到的结果可以在不加休息的情况下按整数取整,因此
number.RoundUp(0.15) => 10.2 check 10.2 / 0.15 = 68
RoundUp(5, 2.25) => 6.75 check 6.75 / 2.25 = 3
RoundUp(5, 2.50) => 5.0 check 5 / 2.5 = 2
您需要将舍入因子乘以除法的上限,例如:
public static decimal RoundUp(this decimal value, decimal round)
{
return Math.Ceiling(value / round) * round;
}
Dotnetfiddle不支持扩展方法,但这是概念证明:https://dotnetfiddle.net/BIkLC3
如果要舍入到下一个小数,则需要分别将整数和小数舍入:
public static decimal RoundUp(decimal number, decimal round)
{
decimal numberDecimal = number - Math.Truncate(number);
decimal roundDecimal = round - Math.Truncate(round);
decimal numberWhole = number - numberDecimal;
decimal roundWhole = round - roundDecimal;
if (roundWhole > 0)
numberWhole = Math.Ceiling(number / roundWhole) * roundWhole;
if (roundDecimal > 0)
roundDecimal = Math.Ceiling(numberDecimal / roundDecimal) * roundDecimal;
return numberWhole + roundDecimal;
}
public static decimal RoundUp(this decimal value, decimal decimals)
{
return Math.Ceiling(value /decimals) * decimals;
}
尽管您不能从字面上使用RoundUp(0.1)进行调用,但必须使用RoundUp(0.1m)
事实证明这很简单:
public static decimal RoundUp(this decimal value, decimal @base)
{
var n = Math.Ceiling((value + @base) / @base) -1;
return (n * @base);
}
}