舍入最接近的0.5
我希望以这种方式完善
13.1, round to 13.5 13.2, round to 13.5 13.3, round to 13.5 13.4, round to 13.5 13.5 = 13.5 13.6, round to 14.0 13.7, round to 14.0 13.8, round to 14.0 13.9, round to 14.0
抱歉我需要以上述方式修改…这样做但不合适
doubleValue = Math.Round((doubleValue * 2), MidpointRounding.ToEven) / 2;
如果需要13.1, round to 13.5
和13.9, round to 14.0
,那么:
double a = 13.1; double rounded = Math.Ceil(a * 2) / 2;
这是有效的,我只是测试了它;
double a = 13.3; var rn = a % 0.5 == 0 ? 1 : 0; Math.Round(a, rn);
一个简单的方法,没有c#的内置方法(如果你想)它的写作我c ++(我曾经缺乏c ++中的圆函数)但你可以很容易地将它改为c#语法
int round(float nNumToRound) { // Variable definition int nResult; // Check if the number is negetive if (nNumToRound > 0) { // its positive, use floor. nResult = floor(nNumToRound + 0.5); } else if (nNumToRound < 0) { // its negtive, use ceil nResult = ceil(nNumToRound - 0.5); } return (nResult);
}
num = (num % 0.5 == 0 ? num : Math.Round(num));
适合您的解决方案inheritance完整的控制台程序
static void Main(string[] args) { double[] a = new double[]{ 13.1,13.2,13.3D,13.4,13.5,13.6,13.7,13.8,13.9,13.58,13.49,13.55, }; foreach (var b in a) { Console.WriteLine("{0}-{1}",b,b % 0.5 == 0 ? b : Math.Round(b)); } Console.ReadKey(); }
如果舍入要求将来发生变化,您只需要将0.5
更改0.5
其他数字
13.6
和13.7
最近0.5
是13.5
,所以你有正确的解决方案。
为你的价值表:
var value = 13.5; var reminder = value % (int)value; var isMiddle = Math.Abs(reminder - 0.5) < 0.001; var result = (isMiddle ? Math.Round(value * 2, MidpointRounding.AwayFromZero): Math.Round(value)*2)/ 2;
我不知道这是否正确,但它确实有效。 如果你想要试试这个:
double doubleValue = 13.5; double roundedValue = 0.0; if (doubleValue.ToString().Contains('.')) { string s = doubleValue.ToString().Substring(doubleValue.ToString().IndexOf('.') + 1); if (Convert.ToInt32(s) == 5) { roundedValue = doubleValue; } else { roundedValue = Math.Round(doubleValue); } } Console.WriteLine("Result: {0}", roundedValue);
var a = d == (((int)d)+0.5) ? d : Math.Round(d);
d是双倍的。