C# 四舍五入最接近的0.5
我想这样圆满结束C# 四舍五入最接近的0.5,c#,rounding,C#,Rounding,我想这样圆满结束 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
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;
这是可行的,我只是测试了一下
double a = 13.3;
var rn = a % 0.5 == 0 ? 1 : 0;
Math.Round(a, rn);
d是一个双精度。对于
13.6
最接近0.5
,13.7
是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;
var值=13.5;
var提醒=值%(整数)值;
var isMiddle=Math.Abs(提醒-0.5)<0.001;
var结果=(isMiddle?Math.Round(值*2,中点Rounding.AwayFromZero):Math.Round(值)*2)/2;
如果13.1和13.9都需要,那么:
double a = 13.1;
double rounded = Math.Ceil(a * 2) / 2;
一种不使用c#的内置方法的简单方法(如果需要)
它写的C++(我曾经缺少C++中的圆函数)
但是你可以很容易地把它改成c#语法
int-round(浮点nNumToRound)
{
//变量定义
结果;
//检查号码是否为负数
如果(nNumToRound>0)
{
//它的正面,使用地板。
nResult=地板(nNumToRound+0.5);
}
否则如果(nNumToRound<0)
{
//它是否定的,用ceil
nResult=ceil(nNumToRound-0.5);
}
返回(nResult);
}
这是完整的控制台程序
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
更改为其他数字我不知道这是否正确,但它确实有效。如果需要,请尝试以下操作:
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);
非常糟糕的解决方案。如果这个数字是14.5,而不是OP的例子中的13.5,你怎么能保持13.5不变呢?但是我需要的是,如果它高于或13.6,它应该四舍五入到下一个数字14.0好的,如果你有13.58,它应该如何四舍五入?13.1,四舍五入到13.5 13.2,四舍五入到13.3,四舍五入到13.5 13.4,四舍五入到13.5 13.5=13.6,四舍五入到14.0 13.7,四舍五入到14.013.8,四舍五入到14.013.9,四舍五入到14.0,而我只有一个小数。我的答案是有效的。这是找到余数最糟糕的方法。我做了什么?:)。我想尽快回答我想这就是原因
num = (num % 0.5 == 0 ? num : Math.Round(num));
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();
}
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);