ลิเทอรัลจำนวนเต็ม (Integer Literals) และ จุดลอยตัว (Floating-point Literals) ใน C#
Integer Literals
ลิเทอรัลจำนวนเต็มสามารถเป็นฐานสิบ (Decimal) หรือฐานสิบหก (Hexadecimal)
- Decimal: ไม่มี Prefix เช่น
10,200 - Hexadecimal: ใช้ Prefix
0xหรือ0Xเช่น0xFF(255) - Suffix:
u/U(unsigned),l/L(long),ul/UL(ulong)
ตัวอย่าง
int a = 200; // decimal
uint b = 300u; // unsigned int
long c = 400L; // long
ulong d = 500UL; // unsigned long
int hex = 0xFF; // 255 decimal
Floating-point Literals
ประกอบด้วยส่วนจำนวนเต็ม จุดทศนิยม ส่วนทศนิยม และเลขยกกำลัง (Exponent)
- Decimal form:
4.89f,3.14159 - Exponential form:
314159E-5F(= 3.14159) - Suffix:
f/F(float),d/D(double),m/M(decimal)
ตัวอย่าง
float f = 4.89f; // float
double d = 3.14159; // double (default)
decimal m = 123.45m; // decimal
double exp = 1.5E2; // 150.0
ตัวอย่างโค้ดแสดงผล
using System;
namespace Demo
{
class Program
{
static void Main()
{
// Integer
int a = 200;
Console.WriteLine("Integer: " + a); // 200
// Floating-point
float b = 4.89f;
Console.WriteLine("Float: " + b); // 4.89
}
}
}
ผลลัพธ์
Integer: 200
Float: 4.89
ตารางเปรียบเทียบ Suffix
| Type | Suffix | ตัวอย่าง |
|---|---|---|
| int | (none) | 10 |
| uint | u / U | 10U |
| long | l / L | 10L |
| ulong | ul / UL | 10UL |
| float | f / F | 3.14f |
| double | d / D / (none) | 3.14 / 3.14d |
| decimal | m / M | 3.14m |