เมธอด Decimal.ToSingle() ใน C# ใช้แปลงค่าของ Decimal ที่ระบุเป็นตัวเลขจุดลอยตัวความแม่นยำเดี่ยว (single-precision floating-point) ที่เทียบเท่า
ไวยากรณ์
public static float ToSingle (decimal val);
พารามิเตอร์ val คือจำนวนทศนิยมที่ต้องการแปลง
ตัวอย่าง
ตัวอย่างที่ 1: แปลงค่าทศนิยมเล็กมากเป็น float
using System;
public class Demo {
public static void Main(){
Decimal val = 0.00000007575833m;
Console.WriteLine("Decimal value = " + val);
float res = Decimal.ToSingle(val);
Console.WriteLine("Single-precision floating-point number = " + res);
}
}
ผลลัพธ์
Decimal value = 0.00000007575833 Single-precision floating-point number = 7.575833E-08
ตัวอย่างเพิ่มเติม
ตัวอย่างที่ 2: แปลงค่าทศนิยมใหญ่เป็น float
using System;
public class Demo {
public static void Main(){
Decimal val = 8767576576m;
Console.WriteLine("Decimal value = " + val);
float res = Decimal.ToSingle(val);
Console.WriteLine("Single-precision floating-point number = " + res);
}
}
ผลลัพธ์
Decimal value = 8767576576 Single-precision floating-point number = 8.767576E+09