Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Phương thức Decimal.Round() trong C#


Phương thức Decimal.Round() trong C# được sử dụng để làm tròn một giá trị thành số nguyên gần nhất hoặc số chữ số thập phân được chỉ định.

Cú pháp

Dưới đây là các nạp chồng của phương thức:

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

Ví dụ 1 - Làm tròn đến số nguyên

Hãy xem ví dụ sau để triển khai phương thức 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 3 = " + val3);
        Console.WriteLine("Value 1 (Rounded) = " + (Decimal.Round(val1)));
        Console.WriteLine("Value 2 (Rounded) = " + (Decimal.Round(val2)));
        Console.WriteLine("Value 3 (Rounded) = " + (Decimal.Round(val3)));
    }
}

Đầu ra

Chương trình sẽ cho ra kết quả sau:

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

Ví dụ 2 - Làm tròn đến số chữ số thập phân cụ thể

Ví dụ khác triển khai phương thức Decimal.Round() với tham số số chữ số thập phân:

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 3 = " + val3);
        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)));
    }
}

Đầu ra

Chương trình sẽ cho ra kết quả sau:

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