String Formatting ใน Java
ใช้ String.format() หรือ System.out.printf() กับ Format Specifiers เริ่มด้วย %
ตัวอย่างโค้ด
public class Demo {
public static void main(String args[]) {
String myStr = " sample.";
// %s = String
String concatStr = String.format("This is a%s", myStr);
// %.4f = Floating point 4 decimal places
String formatStr = String.format("The value is %.4f", 78.92367);
System.out.println(concatStr);
System.out.println(formatStr);
}
}
ผลลัพธ์
This is a sample.
The value is 78.9237
Format Specifiers พื้นฐาน
| Specifier | ประเภท | ตัวอย่าง | ผลลัพธ์ |
%s | String | String.format("%s", "hi") | hi |
%d | Integer (decimal) | String.format("%d", 42) | 42 |
%f | Float/Double | String.format("%f", 3.14) | 3.140000 |
%.2f | Float 2 decimal | String.format("%.2f", 3.14159) | 3.14 |
%x | Hex (lowercase) | String.format("%x", 255) | ff |
%X | Hex (uppercase) | String.format("%X", 255) | FF |
%o | Octal | String.format("%o", 10) | 12 |
%b | Boolean | String.format("%b", true) | true |
%c | Character | String.format("%c", 'A') | A |
%% | Percent sign | String.format("100%%") | 100% |
Flags และ Width/Precision
| Syntax | ความหมาย | ตัวอย่าง |
%10s | Width 10, ชิดขวา | "_____hello" |
%-10s | Width 10, ชิดซ้าย | "hello_____" |
%05d | Width 5, เติม 0 นำหน้า | "00042" |
%+d | แสดงเครื่องหมาย +/- | "+42", "-5" |
%,d | Comma grouping | "1,000,000" |
%(d | ลบในวงเล็บ | "(42)" |
Date/Time Formatting (Java 8+)
LocalDateTime now = LocalDateTime.now();
String formatted = String.format("%tF %tT", now, now);
// 2024-01-15 14:30:45
// หรือใช้ DateTimeFormatter (แนะนำ)
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatted = now.format(fmt);
String.format vs printf vs MessageFormat
| Method | Use Case |
String.format() | สร้าง String object, reusable |
System.out.printf() | พิมพ์ทันที ไม่ต้องเก็บ String |
MessageFormat | Complex patterns, i18n, pluralization |
StringBuilder | Performance critical, many concatenations |