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

C# Decimal.Truncate - ตัดทศนิยมทิ้ง (ไม่ปัดเศษ)

decimal.Truncate() ตัดส่วนทศนิยมทิ้ง คืนค่าส่วนเต็มเท่านั้น ไม่ปัดเศษ (แตกต่างจาก Round)

ตัวอย่างพื้นฐาน

using System;

public class Demo
{
    public static void Main()
    {
        decimal dc = 20.35M;

        // ตัดทศนิยมทิ้ง
        decimal truncated = decimal.Truncate(dc);

        Console.WriteLine($"Original: {dc}");      // 20.35
        Console.WriteLine($"Truncated: {truncated}"); // 20

        // Negative Numbers
        decimal neg = -20.35M;
        Console.WriteLine($"Truncated(-20.35): {decimal.Truncate(neg)}"); // -20 (เข้าสู่ศูนย์)
    }
}

ผลลัพธ์

Original: 20.35
Truncated: 20
Truncated(-20.35): -20

Truncate vs Round vs Floor vs Ceiling

ValueTruncateFloorCeilingRound (AwayFromZero)Round (ToEven)
20.352020212020
20.502020212120
20.992020212121
-20.35-20-21-20-20-20
-20.50-20-21-20-21-20
-20.99-20-21-20-21-21

Math.Truncate (สำหรับ double/float)


double d = 20.35;
double truncated = Math.Truncate(d); // 20.0 (คืน double)

float f = 20.35f;
float truncatedF = Math.Truncate(f); // 20.0f

Integer Division Alternative (สำหรับ Positive Numbers)


// สำหรับ Positive: (int)(value) หรือ value / 1
int truncated = (int)20.35M; // 20 - Explicit Cast

// แต่ Negative แตกต่าง!
(int)(-20.35M) // -20 (Truncate toward zero)
Math.Floor(-20.35) // -21 (Floor toward negative infinity)

กรณีใช้งานจริง

  • Financial: ตัดสตางค์ทิ้ง (ไม่ปัดขึ้น)
  • Pagination: คำนวณจำนวนหน้า `totalItems / pageSize` → Truncate
  • Array Indexing: แปลง Float Coordinate เป็น Index
  • Time Calculation: หน่วยเวลาที่ไม่ต้องการเศษ

⚠️ ข้อผิดพลาดในต้นฉบับ

โค้ดต้นฉบับมี Error: `dc.Truncate(val)` - `Truncate` เป็น Static Method ไม่ใช่ Instance Method และ `val` ไม่ได้ประกาศ

ถูกต้อง: `decimal.Truncate(dc)`

Extension Method สะดวก


public static class DecimalExtensions
{
    public static decimal TruncateDecimals(this decimal d, int decimals)
    {
        if (decimals < 0) throw new ArgumentOutOfRangeException(nameof(decimals));
        if (decimals == 0) return decimal.Truncate(d);

        decimal factor = (decimal)Math.Pow(10, decimals);
        return decimal.Truncate(d * factor) / factor;
    }
}

// ใช้งาน
20.3567M.TruncateDecimals(2) // 20.35 (ตัดทิ้งหลัง 2 ตำแหน่ง)
20.3567M.TruncateDecimals(0) // 20