B-Rad
B-Rad

Reputation: 1557

How can I round up or down in C#?

I have tried using Math.Round and MidpointRounding. This does not appear to do what I need.

Example:

52.34567 rounded to 2 decimals UP   = 52.35
 1.183   rounded to 2 decimals DOWN =  1.18

Do I need to write a custom function?

Sometimes I need a number like 23.567 to round DOWN to 23.56. In this scenario...

Math.Round(dec, 2, MidpointRounding.AwayFromZero) gives 23.57
Math.Round(dec, 2, MidpointRounding.ToEven) gives 23.57

Decimals up to 9 decimal places could come out and need to be rounded to 1, 2, 3 or even 4 decimal places.

Upvotes: 28

Views: 81219

Answers (9)

Arun Kumar Tiwari
Arun Kumar Tiwari

Reputation: 101

You can achieve that by using the method of Math.Round() or decimal.Round():

Math.Round(amt)
Math.Round(amt, Int32) and other overloading methods.

decimal.Round(amt)
decimal.Round(amt, 2) and other overloading methods.

Upvotes: 0

anandd360
anandd360

Reputation: 306

Try this custom rounding:

public int Round(double value)
{
    double decimalpoints = Math.Abs(value - Math.Floor(value));
    if (decimalpoints > 0.5)
        return (int)Math.Round(value);
    else
        return (int)Math.Floor(value);
}

Upvotes: 0

CryogenicNeo
CryogenicNeo

Reputation: 943

The Math class gives you methods to use to round up and down, they are Math.Ceiling() and Math.Floor() respectively. They work like Math.Round(), but they have a particularity, they only receive a value and round them to only the entire part.

So you need to use Math.Pow() to multiply the value by 10 to the n-esimal units you need to round power and then you need to divide by the same multiplied value.

Is important that you note, that the input parameters of the Math.Pow() method are double, so you need to convert them to double.

For example:

When you want to round up the value to 3 decimals (supposing value type is decimal):

double decimalsNumber = 3;
decimal valueToRound = 1.1835675M;
// powerOfTen must be equal to 10^3 or 1000.
double powerOfTen = Math.Pow(10, decimalsNumber);
// rounded must be equal to Math.Ceiling(1.1835675 * 1000) / 1000
decimal rounded = Math.Ceiling(valueToRound * (decimal)powerOfTen) / (decimal)powerOfTen;


Result: rounded = 1.184

When you want to round down the value to 3 decimals (supposing value type is decimal):

double decimalsNumber = 3;
decimal valueToRound = 1.1835675M;
// powerOfTen must be equal to 10^3 or 1000.
double powerOfTen = Math.Pow(10, decimalsNumber);
// rounded must be equal to Math.Floor(1.1835675 * 1000) / 1000
decimal rounded = Math.Floor(valueToRound * (decimal)powerOfTen) / (decimal)powerOfTen;


Result: rounded = 1.183

To reference how to use them more specificaly and to get more information and about both methods you can see these pages from the oficial MSDN Microsoft site:

Math Class

Math.Pow Method (Double, Double)

Math.Floor Method (Decimal)

Math.Floor Method (Double)

Math.Ceiling Method (Decimal)

Math.Ceiling Method (Double)

Upvotes: 1

B-Rad
B-Rad

Reputation: 1557

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);
}

Upvotes: 11

Nikhil S
Nikhil S

Reputation: 21

Complete code with result.

  double a = Math.Round(128.5, 0, MidpointRounding.AwayFromZero);

Result is 129

Upvotes: 2

Albert Tolokonnikov
Albert Tolokonnikov

Reputation: 241

Maybe this?

Math.Round(dec + 0.5m, MidpointRounding.AwayFromZero);

Upvotes: 0

atkretsch
atkretsch

Reputation: 2397

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.

Upvotes: 49

Jeff
Jeff

Reputation: 7674

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

Upvotes: 17

pascalhein
pascalhein

Reputation: 5846

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

Upvotes: 37

Related Questions