C# 数学回合在 0.8 上而不是在 .5 上

C# math round on 0.8 not on .5

假设我这里有 double 类型的数字 87.6 我想对其进行舍入,所以我应用了 C# build in round 方法来获得类似这样的输出

  double test2 = 87.6;
  Console.WriteLine(Math.Round(test2, 0));

这将生成 88,这很好。但是,我想回到 87 我的逻辑是 0.8 而不是 0.5。因此,例如,如果我的输入是 87.8,那么我想得到 88,如果我的输入是 88.7,那么我想将它四舍五入为 87。

我认为这可行:

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);

我在评论区得到了答案,这里是逻辑

double test2 = 87.6;
test2 -= 0.3;
Console.WriteLine(Math.Round(test2, 0));

这个 0.3 会有所不同