3

我想以这种方式四舍五入

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;
4

7 回答 7

8

如果 和 需要它13.1, round to 13.513.9, round to 14.0那么:

double a = 13.1;
double rounded = Math.Ceil(a * 2) / 2;
于 2012-08-31T11:27:17.190 回答
1

这行得通,我刚刚测试过;

double a = 13.3;
var rn  =  a % 0.5 == 0 ? 1 : 0;
Math.Round(a, rn);
于 2012-08-31T11:24:26.637 回答
0

最接近0.5和是13.6,所以你有正确的解决方案。13.713.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;
于 2012-08-31T11:25:59.383 回答
0

一种简单的方法,无需 c# 的内置方法(如果需要)它的 writen i 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);

}

于 2012-08-31T11:27:54.897 回答
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();
        }

如果将来舍入要求发生变化,您只需要更改0.5为其他数字

于 2012-08-31T11:38:15.763 回答
0

我不知道这是否是正确的方法,但它的工作原理。如果你想试试这个:

        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);
于 2012-08-31T11:50:01.537 回答
-1
var a = d == (((int)d)+0.5) ? d : Math.Round(d);

d 是双倍的。

于 2012-08-31T11:25:10.193 回答