Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด Decimal.Round ใน C# พร้อมตัวอย่าง


บทนำ

เมธอด Decimal.Round() ใน C# ใช้สำหรับปัดเศษค่า Decimal ให้เป็นจำนวนเต็มที่ใกล้ที่สุด หรือปัดเศษให้เหลือจำนวนตำแหน่งทศนิยมที่กำหนด รองรับโหมดการปัดเศษต่างๆ ผ่าน MidpointRounding

ไวยากรณ์ (Syntax)

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

ตัวอย่างที่ 1: การปัดเศษเป็นจำนวนเต็ม

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("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 3 = 394949845.14245
Remainder = 9.00
Value 1 (Rounded) = 9
Value 2 (Rounded) = 15
Value 3 (Rounded) = 394949845

ตัวอย่างที่ 2: การปัดเศษกำหนดตำแหน่งทศนิยม

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("Remainder = " + Decimal.Remainder(val1, val2));
        
        Console.WriteLine("Value 1 (Rounded 1 dp) = " + Decimal.Round(val1, 1));
        Console.WriteLine("Value 2 (Rounded 1 dp) = " + Decimal.Round(val2, 1));
        Console.WriteLine("Value 3 (Rounded 2 dp) = " + Decimal.Round(val3, 2));
    }
}

ผลลัพธ์

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

สรุป

เมธอด Decimal.Round() ให้ความยืดหยุ่นสูงในการปัดเศษค่าทศนิยม สามารถระบุจำนวนตำแหน่งทศนิยมและโหมดการปัดเศษ (เช่น AwayFromZero, ToEven) ได้ ซึ่งเหมาะสำหรับการคำนวณทางการเงินที่ต้องการความแม่นยำ