c# - 如何四舍五入到最接近的偶数?
问题描述
我的最后一个目标总是四舍五入到最接近的偶数。
例如,1122.5196
我想要的数字作为 result 1122
。我试过这个选项:
Math.Round(1122.5196d, 0, MidpointRounding.ToEven); // result 1123
Math.Round(1122.5196d, 0, MidpointRounding.AwayFromZero); // result 1123
最后,我想得到的总是最接近的偶数。例如:
1122.51 --> 1122
1122.9 --> 1122
(因为最近的 int 是1123
奇数,并且1122
比更接近1124
)1123.0 --> 1124
(下一个偶数值,下一个更高的偶数值)
我只使用正数。
等等。
有一些方法可以做到这一点,或者我应该实现自己的方法?
解决方案
试试这个(让我们使用Math.Round
withMidpointRounding.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
推荐阅读
- sensors - 我怎样才能嗅探 LoRaWAN 包?
- gwt - CellTable 的事件
- c# - 使用单元格样式和格式将行插入现有表格
- typescript - 如何为使用 set 函数的组件声明类型?
- python - Python 时间算术 - 从 python 日期时间对象中删除 3 小时
- css - 在 CSS 中使用 mix-blend-mode 时如何确定文本的颜色?
- r - 绑定数据框
- node.js - 使用 jose 创建 JWK 和 JWS,但是出现错误“不支持的算法”
- docker - 在 docker 容器中运行我的 websocket-server 时出现奇怪的问题
- sql - 查询每天每秒最大订单