在電商、金融、報表系統中,將數值格式化為標準貨幣格式(如 $123,456,789.12)是基礎需求。Java 提供了強大的 java.text.DecimalFormat 類靈活處理各種數值格式化場景。
NumberFormat 是抽象基類,DecimalFormat 是其最常用的實現類,通過模式字符串精確控制格式化行為。
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class NumberFormatDemo {
public static void main(String[] args) {
// 模式:$ 符號 + 千分位分隔 + 兩位小數
NumberFormat nf = new DecimalFormat("$,###.##");
String testStr = nf.format(123456789.123);
System.out.println(testStr); // 輸出: $123,456,789.12
}
}
| 符號 | 含義 | 示例 |
|---|---|---|
| 0 | 強制顯示數字,不足補 0 | 0000.00 → 0123.45 |
| # | 可選數字,不足不補 0 | ####.## → 123.45 |
| . | 小數點分隔符(按 Locale 解析) | #,###.## → 1,234.56 |
| , | 千分位分組分隔符 | #,### → 1,234 |
| % | 百分比格式(乘 100 加 %) | #% → 50% |
| ¤ | 貨幣符號佔位符(按 Locale 解析) | ¤#,### → $1,234 |
| E | 科學記數法 | 0.###E0 → 1.23E3 |
| ; | 分隔正負數格式 | #,###;(#,###) → (1,234) |
// 標準貨幣(兩位小數,千分位)
new DecimalFormat("¤#,##0.00").format(1234567.5); // $1,234,567.50
// 中文貨幣格式
new DecimalFormat("¥#,##0.00").format(1234567.5); // ¥1,234,567.50
// 無小數位整數貨幣
new DecimalFormat("¤#,##0").format(1234567); // $1,234,567
// 負數用括號表示(會計格式)
new DecimalFormat("¤#,##0.00;(¤#,##0.00)").format(-1234.5); // ($1,234.50)
// 百分比格式
new DecimalFormat("#,##0.00%").format(0.1234); // 12.34%
使用 NumberFormat.getCurrencyInstance(Locale) 自動適應地區貨幣格式:
import java.text.NumberFormat;
import java.util.Locale;
double amount = 1234567.89;
System.out.println(NumberFormat.getCurrencyInstance(Locale.US).format(amount)); // $1,234,567.89
System.out.println(NumberFormat.getCurrencyInstance(Locale.CHINA).format(amount)); // ¥1,234,567.89
System.out.println(NumberFormat.getCurrencyInstance(Locale.GERMANY).format(amount)); // 1.234.567,89 €
System.out.println(NumberFormat.getCurrencyInstance(Locale.JAPAN).format(amount)); // ¥1,234,568
BigDecimal 避免浮點數精度問題