簡體   English   中英

在 C# 中四舍五入到小數點后兩位

[英]Rounding down to 2 decimal places in c#

如何乘以兩位小數並將結果四舍五入到小數點后兩位?

例如,如果方程為 41.75 x 0.1,結果將為 4.175。 如果我在 c# 中使用小數執行此操作,它將自動四舍五入到 4.18。 我想四舍五入到 4.17。

我嘗試使用 Math.Floor 但它只是四舍五入到 4.00。 下面是一個例子:

Math.Floor (41.75 * 0.1);

Math.Round(...)函數有一個 Enum 來告訴它使用什么舍入策略。 不幸的是,這兩個定義並不完全適合您的情況。

兩種中點舍入模式是:

  1. AwayFromZero - 當一個數字在其他兩個數字的中間時,它會向離零最近的數字四舍五入。 (又名,四舍五入)
  2. ToEven - 當一個數字介於其他兩個數字之間時,它會向最接近的偶數四舍五入。 (比 0.17 更喜歡 0.16,比 0.17 更喜歡 0.18)

您要使用的是帶有一些乘法的Floor

var output = Math.Floor((41.75 * 0.1) * 100) / 100;

output變量現在應該有 4.17 了。

事實上,您也可以編寫一個函數來獲取可變長度:

public decimal RoundDown(decimal i, double decimalPlaces)
{
   var power = Convert.ToDecimal(Math.Pow(10, decimalPlaces));
   return Math.Floor(i * power) / power;
}
public double RoundDown(double number, int decimalPlaces)
{
     return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
}

C# 中沒有對精確地板/天花板的原生支持。

但是,您可以通過乘以數字、下限,然后除以相同的乘數來模擬功能。

例如,

decimal y = 4.314M;
decimal x = Math.Floor(y * 100) / 100;  // To two decimal places (use 1000 for 3 etc)
Console.WriteLine(x);  // 4.31

不是理想的解決方案,但如果數量很少,應該可以工作。

.NET Core 3.0和即將推出的.NET Framework 5.0 ,以下內容有效

Math.Round(41.75 * 0.1, 2, MidpointRounding.ToZero)

另一種解決方案是從遠離零舍入到零。 它應該是這樣的:

    static decimal DecimalTowardZero(decimal value, int decimals)
    {
        // rounding away from zero
        var rounded = decimal.Round(value, decimals, MidpointRounding.AwayFromZero);

        // if the absolute rounded result is greater 
        // than the absolute source number we need to correct result
        if (Math.Abs(rounded) > Math.Abs(value))
        {
            return rounded - new decimal(1, 0, 0, value < 0, (byte)decimals);
        }
        else
        {
            return rounded;
        }
    }

這是我的防浮動圓角。

    public static class MyMath
{
    public static double RoundDown(double number, int decimalPlaces)
    {
        string pr = number.ToString();
        string[] parts = pr.Split('.');
        char[] decparts = parts[1].ToCharArray();
        parts[1] = "";
        for (int i = 0; i < decimalPlaces; i++)
        {
            parts[1] += decparts[i];
        }
        pr = string.Join(".", parts);
        return Convert.ToDouble(pr);
    }
}

我發現最好的方法是使用字符串; 數學的二進制變幻莫測往往會出錯,否則。 人們等待 .Net 5.0 使這一事實過時。 沒有小數位是一種特殊情況:您可以使用 Math.Floor 來實現。 否則,我們將小數位數比所需的數字多一位,然后解析沒有最后一位數字的數字以獲得答案:

/// <summary>
/// Truncates a Double to the given number of decimals without rounding
/// </summary>
/// <param name="D">The Double</param>
/// <param name="Precision">(optional) The number of Decimals</param>
/// <returns>The truncated number</returns>
public static double RoundDown(this double D, int Precision = 0)
{
  if (Precision <= 0) return Math.Floor(D);
  string S = D.ToString("0." + new string('0', Precision + 1));
  return double.Parse(S.Substring(0, S.Length - 1));
}

如果您想將任何雙精度舍入到特定的小數位,如果是中點並不重要,您可以使用:

    public double RoundDownDouble(double number, int decimaPlaces)
    {
        var tmp = Math.Pow(10, decimaPlaces);
        return Math.Truncate(number * tmp) / tmp;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM