首页 > 解决方案 > 如何四舍五入到最接近的偶数?

问题描述

我的最后一个目标总是四舍五入到最接近的偶数

例如,1122.5196我想要的数字作为 result 1122。我试过这个选项:

Math.Round(1122.5196d, 0, MidpointRounding.ToEven);       // result 1123
Math.Round(1122.5196d, 0, MidpointRounding.AwayFromZero); // result 1123

最后,我想得到的总是最接近的偶数。例如:

我只使用正数

等等。

有一些方法可以做到这一点,或者我应该实现自己的方法?

标签: c#algorithmmathintegerrounding

解决方案


试试这个(让我们使用Math.RoundwithMidpointRounding.AwayFromZero以获得“下一个偶数值”,但按比例缩放-2因子):

double source = 1123.0;

// 1124.0
double result = Math.Round(source / 2, MidpointRounding.AwayFromZero) * 2;

演示:

double[] tests = new double[] {
     1.0,
  1123.1,
  1123.0,
  1122.9,
  1122.1,
  1122.0,
  1121.5,
  1121.0,
};

string report = string.Join(Environment.NewLine, tests
  .Select(item => $"{item,6:F1} -> {Math.Round(item / 2, MidpointRounding.AwayFromZero) * 2}"));

Console.Write(report);

结果:

   1.0 -> 2     // In case of tie, next even value
1123.1 -> 1124
1123.0 -> 1124  // In case of tie, next even value
1122.9 -> 1122
1122.1 -> 1122
1122.0 -> 1122
1121.5 -> 1122
1121.0 -> 1122  // In case of tie, next even value

推荐阅读