假设我在这里有两个类型为87.6的数字我想绕它,所以我在圆方法中应用了C#build来获得这样的输出
double test2 = 87.6;
Console.WriteLine(Math.Round(test2, 0));
这将产生88,这很好。但是,我想要回到87,我的逻辑将是0.8而不是0.5。因此,例如,如果我的输入是87.8,那么我想得到88,如果我的输入是88.7,那么我想将它舍入到87。
我从评论部分得到的答案是这个的逻辑
double test2 = 87.6;
test2 -= 0.3;
Console.WriteLine(Math.Round(test2, 0));
这0.3将有所作为
我认为这会奏效:
public static class RoundingExtensions {
public static int RoundWithBreak(this valueToRound, double breakValue = .5) {
if (breakValue <= 0 || breakValue >= 1) { throw new Exception("Must be between 0 and 1") }
var difference = breakValue - .5;
var min = Math.Floor(breakValue);
var toReturn = Math.Round(breakValue - difference, 0);
return toReturn < min ? min : toReturn;
}
}
消耗:
var test = 8.7;
var result = test.RoundWithBreak(.8);