如何四舍五入到一半的价值
How to round down to half value
我正在尝试如下舍入。
1.1 -> 1
1.2 -> 1
.
1.4 -> 1
1.5 -> 1.5
1.6 -> 1.5
.
.
1.9 -> 1.5
2 -> 2
我怎样才能做到这一点?我试过 Math.Round(value), Math.Round(value, 1), Math.Round(value,MidpointRounding.AwayFromZero) 似乎没有什么能达到我的需要。非常感谢任何帮助
可以试试:
decimal HalfRound(decimal value)
{
var floor = Math.Floor(value);
return floor += (value - floor) < 0.5M ? 0.0M : 0.5M;
}
让我们针对 OP 的一些数据测试上面的函数:
Console.WriteLine($"1.1 => {HalfRound(1.1M)}");
Console.WriteLine($"1.2 => {HalfRound(1.2M)}");
Console.WriteLine($"1.4 => {HalfRound(1.4M)}");
Console.WriteLine($"1.5 => {HalfRound(1.5M)}");
Console.WriteLine($"1.6 => {HalfRound(1.6M)}");
Console.WriteLine($"1.9 => {HalfRound(1.9M)}");
Console.WriteLine($"2.0 => {HalfRound(2.0M)}");
Console.WriteLine($"3.5 => {HalfRound(3.5M)}");
Console.WriteLine($"3.6 => {HalfRound(3.6M)}");
Console.WriteLine($"3.9 => {HalfRound(3.9M)}");
结果:
//1.1 => 1.0
//1.2 => 1.0
//1.4 => 1.0
//1.5 => 1.5
//1.6 => 1.5
//1.9 => 1.5
//2.0 => 2.0
//3.5 => 3.5
//3.6 => 3.5
//3.9 => 3.5
我正在尝试如下舍入。
1.1 -> 1
1.2 -> 1
.
1.4 -> 1
1.5 -> 1.5
1.6 -> 1.5
.
.
1.9 -> 1.5
2 -> 2
我怎样才能做到这一点?我试过 Math.Round(value), Math.Round(value, 1), Math.Round(value,MidpointRounding.AwayFromZero) 似乎没有什么能达到我的需要。非常感谢任何帮助
可以试试:
decimal HalfRound(decimal value)
{
var floor = Math.Floor(value);
return floor += (value - floor) < 0.5M ? 0.0M : 0.5M;
}
让我们针对 OP 的一些数据测试上面的函数:
Console.WriteLine($"1.1 => {HalfRound(1.1M)}");
Console.WriteLine($"1.2 => {HalfRound(1.2M)}");
Console.WriteLine($"1.4 => {HalfRound(1.4M)}");
Console.WriteLine($"1.5 => {HalfRound(1.5M)}");
Console.WriteLine($"1.6 => {HalfRound(1.6M)}");
Console.WriteLine($"1.9 => {HalfRound(1.9M)}");
Console.WriteLine($"2.0 => {HalfRound(2.0M)}");
Console.WriteLine($"3.5 => {HalfRound(3.5M)}");
Console.WriteLine($"3.6 => {HalfRound(3.6M)}");
Console.WriteLine($"3.9 => {HalfRound(3.9M)}");
结果:
//1.1 => 1.0
//1.2 => 1.0
//1.4 => 1.0
//1.5 => 1.5
//1.6 => 1.5
//1.9 => 1.5
//2.0 => 2.0
//3.5 => 3.5
//3.6 => 3.5
//3.9 => 3.5