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


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

在C#中,MathF.Round()是MathF類方法,用於將值四舍五入到最接近的整數或小數位數。可以通過更改傳遞的參數的數量和類型來重載此方法。 MathF.Round()方法的重載列表中有4種方法。

  1. MathF.Round(Single)方法
  2. MathF.Round(Single,Int32)方法
  3. MathF.Round(Single,Int32,MidpointRounding)方法
  4. MathF.Round(Single,MidpointRounding)方法

在這裏,我們將討論前兩種方法。



MathF.Round(Single) Method

此方法將單精度浮點值舍入為最接近的整數值。

用法: public static float Round (float x);
Here, x is a singlefloating-point number which is to be rounded. Type of this parameter is System.Single.

返回類型:它返回最接近x的整數,返回類型為System.Single。

注意:如果x的小數部分位於兩個整數的中間,其中一個為偶數,另一個為奇數,則返回偶數。

例:

// C# program to demonstrate the 
// MathF.Round(Single) method 
using System; 
  
class Geeks { 
  
    // Main method 
    static void Main(string[] args) 
    { 
  
        // Case-1 
        // A float value whose fractional part is 
        // less than the halfway between two 
        // consecutive integers 
        float dx1 = 12.434565f; 
  
        // Output value will be 12 
        Console.WriteLine("Rounded value of " + dx1 + 
                          " is " + MathF.Round(dx1)); 
  
        // Case-2 
        // A float value whose fractional part is 
        // greater than the halfway between two 
        // consecutive integers 
        float dx2 = 12.634565f; 
  
        // Output value will be 13 
        Console.WriteLine("Rounded value of " + dx2 + 
                          " is " + MathF.Round(dx2)); 
    } 
}
輸出:
Rounded value of 12.43456 is 12
Rounded value of 12.63457 is 13

MathF.Round(Single, Int32) Method

此方法將單個精度浮點值舍入為指定數量的小數位數。

用法: public static float Round (float x, int digits);

參數:
x:要舍入的單個浮點數。此參數的類型為System.Single。 y:這是返回值中的小數位數。此參數的類型為System.Int32。

返回類型:它返回最接近x的整數,其中包含與y相等的小數位數,返回類型為System.Single。

異常:如果y的值小於0或大於15,則此方法將提供ArgumentOutOfRangeException。

例:

// C# program to demonstrate the 
// MathF.Round(Single, Int32) Method 
using System; 
  
class Geeks { 
  
    // Main method 
    static void Main(string[] args) 
    { 
  
        // float type 
        float dx1 = 12.434565f; 
  
        // using method 
        Console.WriteLine("Rounded value of " + dx1 + 
                      " is " + MathF.Round(dx1, 4)); 
  
        // float type 
        float dx2 = 12.634565f; 
  
        // using method 
        Console.WriteLine("Rounded value of " + dx2 + 
                       " is " + MathF.Round(dx2, 2)); 
    } 
}
輸出:
Rounded value of 12.43456 is 12.4346
Rounded value of 12.63457 is 12.63



相關用法


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