Rounding of nearest 0.5

后端 未结 7 1089
灰色年华
灰色年华 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:20

    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;
    

提交回复
热议问题