基数为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 注: RoundUp by @basis表示结果可以在@基础上除尽,而不包括其余部分:
RoundUp(10.12345m, 0.15) => 10.2 check 10.2 / 0.15 = 68 邻域为10.05和10.35,因此10.12345的正确舍入为10.2
RoundUp(5, 2.25) => 6.75 check 6.75 / 2.25 = 3也就是说,2.25x2 =4.50小于5。因此,5向上舍入2.25将是6.75。
RoundUp(5, 2.50) => 5.0 check 5 / 2.5 = 2 发布于 2020-05-29 19:14:11
您需要将舍入因子乘以除法的上限,如下所示:
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;
}发布于 2020-05-29 18:55:55
public static decimal RoundUp(this decimal value, decimal decimals)
{
return Math.Ceiling(value /decimals) * decimals;
}尽管你不能直接用RoundUp(0.1)来调用它,但你必须使用RoundUp(0.1m)
发布于 2020-05-29 19:43:46
事实证明这是一个非常简单的数学问题:
public static decimal RoundUp(this decimal value, decimal @base)
{
var n = Math.Ceiling((value + @base) / @base) -1;
return (n * @base);
}
}https://stackoverflow.com/questions/62083961
复制相似问题