Rounding of nearest 0.5

后端 未结 7 1084
灰色年华
灰色年华 2021-01-14 16:03

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, roun         


        
7条回答
  •  别那么骄傲
    2021-01-14 16:25

    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

提交回复
热议问题