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

จัดการทศนิยมด้วยตัวดำเนินการตัวเลขใน C#

ชนิด decimal รองรับตัวดำเนินการคณิตศาสตร์มาตรฐาน: +, -, *, /, % ทำงานคล้ายชนิดตัวเลขอื่น แต่มีความแม่นยำสูง

ตัวอย่าง: บวกและลบ Decimal

using System;

class Demo
{
    static void Main()
    {
        decimal d1 = 9.5M;
        decimal d2 = 4.2M;
        
        d1 = d1 + d2;
        Console.WriteLine("Addition of Decimals: " + d1); // 13.7
        
        d1 = d1 - d2;
        Console.WriteLine("Subtraction of Decimals: " + d1); // 9.5
    }
}

ผลลัพธ์

Addition of Decimals: 13.7
Subtraction of Decimals: 9.5

หลักสำคัญ: ต้องเติม Suffix M (หรือ m) ต่อท้ายตัวเลขทศนิยมเพื่อบอกว่าเป็น Decimal Literal