44

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.

handles
  • 7,639
  • 17
  • 63
  • 85

4 Answers4

87

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

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
12

Alternatively, you can use UltimateRoundingFunction given in this blog: http://rajputyh.blogspot.in/2014/09/the-ultimate-rounding-function.html

//amountToRound => input amount
//nearestOf => .25 if round to quater, 0.01 for rounding to 1 cent, 1 for rounding to $1
//fairness => btween 0 to 0.9999999___.
//            0 means floor and 0.99999... means ceiling. But for ceiling, I would recommend, Math.Ceiling
//            0.5 = Standard Rounding function. It will round up the border case. i.e. 1.5 to 2 and not 1.
//            0.4999999... non-standard rounding function. Where border case is rounded down. i.e. 1.5 to 1 and not 2.
//            0.75 means first 75% values will be rounded down, rest 25% value will be rounded up.
decimal UltimateRoundingFunction(decimal amountToRound, decimal nearstOf, decimal fairness)
{
    return Math.Floor(amountToRound / nearstOf + fairness) * nearstOf;
}

Call below for standard rounding. i.e. 1.125 will be rounded to 1.25

UltimateRoundingFunction(amountToRound, 0.25m, 0.5m);

Call below for rounding down border values. i.e. 1.125 will be rounded to 1.00

UltimateRoundingFunction(amountToRound, 0.25m, 0.4999999999999999m);

So called "Banker's Rounding" is not possible with UltimateRoundingFunction, you have to go with paxdiablo's answer for that support :)

Liam
  • 27,717
  • 28
  • 128
  • 190
Yogee
  • 1,412
  • 14
  • 22
0

Notice: This isn't a thing you do in a script.

If you have something like this:

    this.transform.position = new Vector3(
    x: Mathf.Round(this.transform.position.x) + direction.x,
    y: Mathf.Round(this.transform.position.y) + direction.y,
    z: 0.0f
    );

Then go to Unity > Project Settings > Time And then you can change the time.

-1

An extension method based on this answer.

namespace j
{
    public static class MathHelpers
    {
        public static decimal RoundToNearestQuarter(this decimal x)
        {
            return Math.Round(x * 4, MidpointRounding.ToEven) / 4;
        }
    }
}
Jesus is Lord
  • 14,971
  • 11
  • 66
  • 97