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


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


在這裏,我們將了解Math 類的Round() 方法。此方法用於將浮點數四舍五入為最接近的整數值。這個方法重載了 8 次。

用法:

    Decimal     Math.Round(Decimal)
    Double      Math.Round(Double)
    Decimal     Math.Round(Decimal, Int32)
    Decimal     Math.Round(Decimal, MidpointRounding)
    Double      Math.Round(Double, Int32)
    Double      Math.Round(Double, MidpointRounding)
    Decimal     Math.Round(Decimal, Int32, MidpointRounding)
    Double      Math.Round(Double, Int32, MidpointRounding)

參數:

在這裏,我們根據重載方法傳遞雙精度值和十進製值來對給定值進行四舍五入。

返回值:

此方法根據重載的方法返回雙精度值或十進製值。

程序:

下麵給出了演示使用Math 類的Round() 方法的源代碼。給定的程序已成功編譯並執行。

using System;
class Sample
{
    //Entry point of Program
    static public void Main()
    {
        double val = 0.0;
        decimal decVal = 0.0M;

        Console.WriteLine("Demonstration of Round Method:");
        val = Math.Round(2.4);
        Console.WriteLine("Value:"+val);

        val = Math.Round(2.5);
        Console.WriteLine("Value:" + val);

        val = Math.Round(2.6);
        Console.WriteLine("Value:" + val);

        val = Math.Round(2.4567,2);
        Console.WriteLine("Value:" + val);

        val = Math.Round(2.4567, 3);
        Console.WriteLine("Value:" + val);

        decVal = Math.Round(2.4567M, 2);
        Console.WriteLine("Decimal Value:" + decVal);

        decVal = Math.Round(2.4567M,MidpointRounding.AwayFromZero);
        Console.WriteLine("Decimal Value:" + decVal);
    }
}

輸出:

Demonstration of Round Method:
Value:2
Value:2
Value:3
Value:2.46
Value:2.457
Decimal Value:2.46
Decimal Value:2
Press any key to continue . . .



相關用法


注:本文由純淨天空篩選整理自 C# program to demonstrate the use of Round() method of Math class。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。