在C#中将小数舍入到最接近的四分之一

bpl*_*lus 36 c# decimal rounding

在c#中有一个简单的方法可以将小数舍入到最接近的四分之一iex0,x.25,x.50 x.75,例如0.21将舍入到0.25,5.03将舍入到5.0

在此先感谢您的帮助.

pax*_*blo 66

将它乘以4,将其四舍五入,然后再将其除以四:

x = Math.Round (x * 4, MidpointRounding.ToEven) / 4;
Run Code Online (Sandbox Code Playgroud)

四舍五入的各种选项及其解释可以在这里的优秀答案中找到 :-)


Yog*_*gee 10

或者,您可以使用此博客中提供的UltimateRoundingFunction:http: //rajputyh.blogspot.in/2014/09/the-ultimate-rounding-function.html

//amountToRound => input amount
//nearestOf => .25 if round to quater, 0.01 for rounding to 1 cent, 1 for rounding to $1
//fairness => btween 0 to 0.9999999___.
//            0 means floor and 0.99999... means ceiling. But for ceiling, I would recommend, Math.Ceiling
//            0.5 = Standard Rounding function. It will round up the border case. i.e. 1.5 to 2 and not 1.
//            0.4999999... non-standard rounding function. Where border case is rounded down. i.e. 1.5 to 1 and not 2.
//            0.75 means first 75% values will be rounded down, rest 25% value will be rounded up.
decimal UltimateRoundingFunction(decimal amountToRound, decimal nearstOf, decimal fairness)
{
    return Math.Floor(amountToRound / nearstOf + fairness) * nearstOf;
}
Run Code Online (Sandbox Code Playgroud)

请拨打以下标准舍入.即1.125将四舍五入至1.25

UltimateRoundingFunction(amountToRound, 0.25m, 0.5m);
Run Code Online (Sandbox Code Playgroud)

请在下面调用以舍入边界值.即1.125将四舍五入为1.00

UltimateRoundingFunction(amountToRound, 0.25m, 0.4999999999999999m);
Run Code Online (Sandbox Code Playgroud)

所谓的"Banker's Rounding"是不可能使用UltimateRoundingFunction,你必须使用paxdiablo的答案来获得支持:)