Rounding of nearest 0.5

2020-03-26 08:09发布

I want to be rounded off this way

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

sorry for modification i need in the above way... did this way but not appropriate

doubleValue = Math.Round((doubleValue * 2), MidpointRounding.ToEven) / 2;

标签: c# rounding
7条回答
爷的心禁止访问
2楼-- · 2020-03-26 08:25
var a = d == (((int)d)+0.5) ? d : Math.Round(d);

d is a double.

查看更多
爷、活的狠高调
3楼-- · 2020-03-26 08:35

If it is required for 13.1, round to 13.5 and 13.9, round to 14.0, then:

double a = 13.1;
double rounded = Math.Ceil(a * 2) / 2;
查看更多
啃猪蹄的小仙女
4楼-- · 2020-03-26 08:35

Nearest 0.5 for 13.6 and 13.7 is 13.5, so you have correct solution.

for yours table of values:

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;
查看更多
▲ chillily
5楼-- · 2020-03-26 08:37
num = (num % 0.5 == 0 ? num : Math.Round(num));

works well for you solution heres the complete console program

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();
        }

you simply would need to change 0.5 to some other number if the rounding requirement changes in future

查看更多
仙女界的扛把子
6楼-- · 2020-03-26 08:38

I don't know if it is proper way, but it works. Try this if you want:

        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);
查看更多
Rolldiameter
7楼-- · 2020-03-26 08:49

This works, I just tested it;

double a = 13.3;
var rn  =  a % 0.5 == 0 ? 1 : 0;
Math.Round(a, rn);
查看更多
登录 后发表回答