Round a decimal to the nearest quarter in C#

前端 未结 2 2023
不思量自难忘°
不思量自难忘° 2020-12-01 10:04

Is there a simple way in c# to round a decimal to the nearest quarter i.e. x.0, x.25, x.50 x.75 for example 0.21 would round to 0.25, 5.03 would round to 5.0

Thanks

2条回答
  •  青春惊慌失措
    2020-12-01 10:53

    Multiply it by four, round it as you need to an integer, then divide it by four again:

    x = Math.Round (x * 4, MidpointRounding.ToEven) / 4;
    

    The various options for rounding, and their explanations, can be found in this excellent answer here :-)

提交回复
热议问题