首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 實現金額千分位格式化:NumberFormat 與 DecimalFormat 兩種標準方式

     編輯:Java 相關知識

標準庫一行代碼搞定

1. 純千分位分隔(無貨幣符號)

String formatted = DecimalFormat.getNumberInstance().format(1245600000);
// 結果: "1,245,600,000"

2. 貨幣格式(含符號、小數位)

String currency = NumberFormat.getCurrencyInstance().format(1245600000);
// 結果: "¥1,245,600,000.00" (視 Locale 而定)

3. 自定義格式(精確控制)

DecimalFormat df = new DecimalFormat("#,##0.00");
String custom = df.format(1245600000.567);
// 結果: "1,245,600,000.57" (四捨五入)

完整示例

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class MoneyFormatDemo {
    public static void main(String[] args) {
        long amount = 1245600000L;
        
        // 千分位
        String number = DecimalFormat.getNumberInstance().format(amount);
        System.out.println("千分位: " + number); // 1,245,600,000
        
        // 貨幣格式 (默認 Locale.CHINA → ¥)
        String currency = NumberFormat.getCurrencyInstance().format(amount);
        System.out.println("貨幣格式: " + currency); // ¥1,245,600,000.00
        
        // 指定 Locale
        String usCurrency = NumberFormat.getCurrencyInstance(Locale.US).format(amount);
        System.out.println("美元格式: " + usCurrency); // $1,245,600,000.00
        
        // 百分比格式
        String percent = NumberFormat.getPercentInstance().format(0.1234);
        System.out.println("百分比: " + percent); // 12%
    }
}

前端 JavaScript 實現(備查)

function toThousands(num) {
    return (num + '').replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
// 或正則替換法
function convert(num) {
    var str = num + "";
    var reg = /(-?\d+)(\d{3})/;
    while (reg.test(str)) {
        str = str.replace(reg, "$1,$2");
    }
    return str;
}
console.log(toThousands(1245600000)); // "1,245,600,000"

最佳實踐建議

  • 後端格式化:使用 NumberFormat.getCurrencyInstance(Locale) 保證國際化正確
  • 前端顯示:傳遞原始數值,前端按用戶 Locale 格式化(Intl.NumberFormat)
  • 存儲/計算:始終使用 BigDecimal 或長整型(分為單位),**永不**存儲格式化字符串
  • 線程安全:DecimalFormat 非線程安全,併發環境用 ThreadLocal 或每次新建

Locale 對照表

Locale貨幣符號千分位小數點
CHINA¥,.
US$,.
GERMANY€.,
FRANCE€空格,
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved