使用C#,我需要一种优雅的方法将一个精度为1/8的数字四舍五入到精度为1/2,并遵循以下规则:
Round(0) = 0
Round(0.125) = 0
Round(0.25) = 0
Round(0.375) = 0.5
Round(0.5) = 0.5
Round(0.625) = 0.5
Round(0.75) = 0.5
Round(0.875) = 1
Round(1) = 1
当然我并不仅限于介于0和1之间的数字。有没有一种不需要过多条件语句的好方法呢?
使用C#,我需要一种优雅的方法将一个精度为1/8的数字四舍五入到精度为1/2,并遵循以下规则:
Round(0) = 0
Round(0.125) = 0
Round(0.25) = 0
Round(0.375) = 0.5
Round(0.5) = 0.5
Round(0.625) = 0.5
Round(0.75) = 0.5
Round(0.875) = 1
Round(1) = 1
当然我并不仅限于介于0和1之间的数字。有没有一种不需要过多条件语句的好方法呢?
public decimal MyRound(decimal input)
{
return Math.Round(input*2-0.001M, MidpointRounding.AwayFromZero)/2;
}
void Main()
{
var testvalues = new decimal[]{0M,0.125M,0.25M,0.375M,0.5M,0.625M,0.75M,0.875M,1M};
foreach (var value in testvalues)
{
Console.WriteLine(String.Format("{0} rounds to {1}",value, MyRound(value)));
}
}
Output:
0 rounds to 0
0.125 rounds to 0
0.25 rounds to 0
0.375 rounds to 0.5
0.5 rounds to 0.5
0.625 rounds to 0.5
0.75 rounds to 0.5
0.875 rounds to 1
1 rounds to 1
我应该指出,我使用十进制只是因为我脑海中认为这就是你在使用的(我觉得是因为我的大脑里有“小数位”。这种技术同样适用于双精度浮点数...
public double Round(double input)
{
var rounded = Math.Round(input*2-0.0001)/2;
return rounded;
}