當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C# Decimal.Round()用法及代碼示例

C# 中的 Decimal.Round() 方法用於將值四舍五入到最接近的整數或指定的小數位數。

用法

以下是語法 -

public static decimal Round (decimal d);
public static decimal Round (decimal d, int decimals);
public static decimal Round (decimal d, MidpointRounding mode);
public static decimal Round (decimal d, int decimals, MidpointRounding mode);

示例

現在讓我們看一個實現 Decimal.Round() 方法的例子 -

using System;
public class Demo {
   public static void Main(){
      Decimal val1 = 9.00m;
      Decimal val2 = 15.29m;
      Decimal val3 = 394949845.14245M;
      Console.WriteLine("Decimal 1 = "+val1);
      Console.WriteLine("Decimal 2 = "+val2);
      Console.WriteLine("Decimal 2 = "+val2);
      Console.WriteLine("Remainder = "+(Decimal.Remainder(val1,val2)));
      Console.WriteLine("Value 1 (Rounded) = "+(Decimal.Round(val1)));
      Console.WriteLine("Value 2 (Rounded) = "+(Decimal.Round(val2)));
      Console.WriteLine("Value 3 (Rounded) = "+(Decimal.Round(val3)));
   }
}

輸出

這將產生以下輸出 -

Decimal 1 = 9.00
Decimal 2 = 15.29
Decimal 2 = 15.29
Remainder = 9.00
Value 1 (Rounded) = 9
Value 2 (Rounded) = 15
Value 3 (Rounded) = 394949845

示例

現在讓我們看另一個實現 Decimal.Round() 方法的例子 -

using System;
public class Demo {
   public static void Main(){
      Decimal val1 = 6.59m;
      Decimal val2 = 30.12m;
      Decimal val3 = 6946649845.25245M;
      Console.WriteLine("Decimal 1 = "+val1);
      Console.WriteLine("Decimal 2 = "+val2);
      Console.WriteLine("Decimal 2 = "+val2);
      Console.WriteLine("Remainder = "+(Decimal.Remainder(val1,val2)));
      Console.WriteLine("Value 1 (Rounded) = "+(Decimal.Round(val1,1)));
      Console.WriteLine("Value 2 (Rounded) = "+(Decimal.Round(val2,1)));
      Console.WriteLine("Value 3 (Rounded) = "+(Decimal.Round(val3,2)));
   }
}

輸出

這將產生以下輸出 -

Decimal 1 = 6.59
Decimal 2 = 30.12
Decimal 2 = 30.12
Remainder = 6.59
Value 1 (Rounded) = 6.6
Value 2 (Rounded) = 30.1
Value 3 (Rounded) = 6946649845.25

相關用法


注:本文由純淨天空篩選整理自AmitDiwan大神的英文原創作品 Decimal.Round() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。