Search code examples
c#decimalrounding

Round a decimal to the nearest quarter in C#


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 in advance for any help.


Solution

  • 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 :-)