如何在 C# 中向上或向下舍入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13482159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:42:48  来源:igfitidea点击:

How to round up or down in C#?

c#math

提问by B-Rad

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

我曾尝试使用 Math.Round 和 MidpointRounding。这似乎没有做我需要的。

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

有时我需要像 23.567 这样的数字来四舍五入到 23.56。在这种情况下...

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.

可能会出现最多 9 位小数的小数,需要四舍五入到 1、2、3 甚至 4 位小数。

采纳答案by atkretsch

Try using decimal.Round():

尝试使用decimal.Round():

decimal.Round(x, 2)

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

x您的值在哪里,2 是您希望保留的小数位数。

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

您还可以通过传递第三个参数来指定 .5 是向上还是向下舍入:

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 numDigitsabove should be how many digits you want to KEEP, not the total number of decimals, etc.

Truncate() 去掉小数的非整数部分。注意numDigits上面应该是你想保留的位数,而不是小数的总数等。

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.

最后,如果您想强制向上取整(截断实际上是强制向下取整),您只需Truncate()在再次除法之前将调用结果加 1 。

回答by pascalhein

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

尝试使用Math.Ceiling(up) 或Math.Floor(down)。例如Math.Floor(1.8) == 1.

回答by Jeff E

Assuming you're using the decimaltype for your numbers,

假设您使用的decimal是数字类型,

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

回答by B-Rad

For a shorter version of the accepted answer, here are the RoundUpand RoundDownfunctions that can be used:

对于已接受答案的较短版本,以下是可以使用的RoundUpRoundDown函数:

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

回答by Albert Tolokonnikov

Maybe this?

也许这个?

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

回答by Nikhil S

Complete code with result.

带结果的完整代码。

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

Result is129

结果是129

回答by anand360

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

回答by CryogenicNeo

The Mathclass 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.

Math班为您提供的方法来使用,以圆上下,他们Math.Ceiling()Math.Floor()分别。它们的工作方式类似于Math.Round(),但它们有一个特殊性,它们只接收一个值并将它们四舍五入到整个部分。

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.

因此,您需要使用Math.Pow()将值乘以 10 到您需要舍入功率的 n 小单位,然后您需要除以相同的乘法值。

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

需要注意的Math.Pow()double,该方法的输入参数是,因此您需要将它们转换为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

当您想将值四舍五入到 3 位小数时(假设值类型为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

当您要将值四舍五入到 3 位小数时(假设值类型为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:

要更具体地参考如何使用它们并获取有关这两种方法的更多信息,您可以从微软官方 MSDN 站点查看这些页面:

Math Class

数学课

Math.Pow Method (Double, Double)

Math.Pow 方法(双、双)

Math.Floor Method (Decimal)

Math.Floor 方法(十进制)

Math.Floor Method (Double)

Math.Floor 方法(双)

Math.Ceiling Method (Decimal)

Math.Ceiling 法(十进制)

Math.Ceiling Method (Double)

Math.Ceiling 方法(双)

回答by Arun Kumar Tiwari

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

您可以通过使用 Math.Round() 或 decimal.Round()- 的方法来实现:

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


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