บทนำ
เมธอด Decimal.ToInt16() ใน C# ใช้แปลงค่าของ Decimal ที่ระบุให้เป็นจำนวนเต็ม 16 บิตที่มีเครื่องหมาย (short) เทียบเท่า โดยตัดส่วนทศนิยมทิ้ง
ไวยากรณ์ (Syntax)
public static short ToInt16 (decimal val);
โดยที่ val คือค่าทศนิยมที่ต้องการแปลง
ตัวอย่างที่ 1: การแปลงค่าบวกและลบ
using System;
public class Demo
{
public static void Main()
{
Decimal val1 = -3.578m;
Decimal val2 = 9.352m;
Console.WriteLine("Decimal 1 = " + val1);
Console.WriteLine("Decimal 2 = " + val2);
short res1 = Decimal.ToInt16(val1);
short res2 = Decimal.ToInt16(val2);
Console.WriteLine("16-bit signed integer (val1) = " + res1);
Console.WriteLine("16-bit signed integer (val2) = " + res2);
}
}
ผลลัพธ์
Decimal 1 = -3.578 Decimal 2 = 9.352 16-bit signed integer (val1) = -3 16-bit signed integer (val2) = 9
ตัวอย่างที่ 2: การแปลงค่าทศนิยมเล็ก
using System;
public class Demo
{
public static void Main()
{
Decimal val1 = 0.001m;
Decimal val2 = 1.000m;
Console.WriteLine("Decimal 1 = " + val1);
Console.WriteLine("Decimal 2 = " + val2);
short res1 = Decimal.ToInt16(val1);
short res2 = Decimal.ToInt16(val2);
Console.WriteLine("16-bit signed integer (val1) = " + res1);
Console.WriteLine("16-bit signed integer (val2) = " + res2);
}
}
ผลลัพธ์
Decimal 1 = 0.001 Decimal 2 = 1.000 16-bit signed integer (val1) = 0 16-bit signed integer (val2) = 1
สรุป
เมธอด Decimal.ToInt16() แปลง Decimal เป็น short (Int16) โดย truncate ส่วนทศนิยม ขอบเขตค่าที่รองรับคือ -32,768 ถึง 32,767 หากค่า Decimal อยู่นอกขอบเขตนี้ จะเกิด OverflowException