ภาพรวม
ใช้ Convert.ToDecimal() แปลง int (Int32) เป็น decimal ซึ่งเป็นการแปลงแบบขยายชนิด ทำได้เสมอโดยไม่สูญเสียความแม่นยำ
รูปแบบการใช้งาน
int val = 2923; decimal decVal = Convert.ToDecimal(val); // 2923.00
ตัวอย่างโค้ดเต็ม
using System;
public class Demo
{
public static void Main()
{
int val = 2923;
decimal decVal = Convert.ToDecimal(val);
Console.WriteLine("Converted Int32 {0} to decimal {1:N2} value", val, decVal);
}
}
ผลลัพธ์
Converted Int32 2923 to decimal 2,923.00 value
วิธีอื่นๆ
decimal decVal = val;- implicit conversion ได้โดยตรงdecimal decVal = (decimal)val;- explicit cast ก็ได้- แนะนำให้ใช้ implicit conversion (
decimal d = val;) เพื่อความอ่านง่ายและประสิทธิภาพ