เมธอด Convert.ToDecimal() แปลงค่าที่ระบุ (string, int, float, double, เป็นต้น) เป็นชนิด decimal ซึ่งมีความแม่นยำสูง เหมาะสำหรับการคำนวณทางการเงิน
ตัวอย่างแปลงจาก String
string stringVal = "2,345.26"; decimal decimalVal = Convert.ToDecimal(stringVal); // 2345.26
ตัวอย่างโค้ดเต็ม
using System;
public class Demo
{
public static void Main()
{
string stringVal = "2,345.26";
decimal decimalVal = Convert.ToDecimal(stringVal);
Console.WriteLine("String converted to decimal = {0}", decimalVal);
}
}
ผลลัพธ์
String converted to decimal = 2345.26
ข้อยกเว้น: โยน FormatException หากสตริงรูปแบบไม่ถูกต้อง, OverflowException หากค่ามีขนาดใหญ่เกินกว่า Decimal.MaxValue