How to round up or down in C#?

Try using decimal.Round():

decimal.Round(x, 2)

Where x is your value and 2 is the number of decimals you wish to keep.

You can also specify whether .5 rounds up or down by passing third parameter:

decimal.Round(x, 2, MidpointRounding.AwayFromZero);

EDIT:

In light of the new requirement (i.e. that numbers are sometimes rounded down despite being greater than "halfway" to the next interval), you can try:

var pow = Math.Pow(10, numDigits);
var truncated = Math.Truncate(x*pow) / pow;

Truncate() lops off the non-integer portion of the decimal. Note that numDigits above should be how many digits you want to KEEP, not the total number of decimals, etc.

Finally, if you want to force a round up (truncation really is a forced round-down), you would just add 1 to the result of the Truncate() call before dividing again.


Assuming you're using the decimal type for your numbers,

static class Rounding
{
    public static decimal RoundUp(decimal number, int places)
    {
        decimal factor = RoundFactor(places);
        number *= factor;
        number = Math.Ceiling(number);
        number /= factor;
        return number;
    }

    public static decimal RoundDown(decimal number, int places)
    {
        decimal factor = RoundFactor(places);
        number *= factor;
        number = Math.Floor(number);
        number /= factor;
        return number;
    }

    internal static decimal RoundFactor(int places)
    {
        decimal factor = 1m;

        if (places < 0)
        {
            places = -places;
            for (int i = 0; i < places; i++)
                factor /= 10m;
        }

        else
        {
            for (int i = 0; i < places; i++)
                factor *= 10m;
        }

        return factor;
    }
}

Example:

Rounding.RoundDown(23.567, 2) prints 23.56

For a shorter version of the accepted answer, here are the RoundUp and RoundDown functions that can be used:

public double RoundDown(double number, int decimalPlaces)
{
    return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
}

public double RoundUp(double number, int decimalPlaces)
{
    return Math.Ceiling(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
}

Try using Math.Ceiling (up) or Math.Floor (down). e.g Math.Floor(1.8) == 1.

Tags:

C#

Math