简体   繁体   中英

How to round up or down in C#?

I have tried using Math.Round & 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?

Edit:

I should have been more specific.

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.

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 (ie 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.

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

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

Complete code with result.

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

Result is 129

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)

也许这个吗?

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

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

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 overloding methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM