DecimalFormat 價格格式化 顯示的問題 和 解決辦法

DecimalFormat 價格格式化顯示的問題

使用 DecimalFormat 格式化的時候,會遇到價格低於三位數時,格式化顯示問題。

Long 轉 String

public class FormatPriceUtil {
    public static String formatPrice(Long price) {
        Optional<Long> price1 = Optional.ofNullable(price);
        return price1.map((Long price2) -> {
            if (price < 100) {
                DecimalFormat nf = new DecimalFormat("##,###,###.##");
                String priceStr = nf.format((double) (price) / 100);
                return priceStr;
            } else {
                DecimalFormat nf = new DecimalFormat("###,###.00");
                String priceStr = nf.format((double) (price) / 100);
                return priceStr;
            }
        }).orElse(OrderResponseCode.FORMAT_PRICE_ISNULL.getMsg());
    }
}

String 轉 long

    long refund_amount_format = (new BigDecimal(refundAmountString).multiply(new BigDecimal("100"))).longValue();
        //支付價格
    long transactionPricez = (new BigDecimal(refundAmountString).multiply(new BigDecimal("100"))).longValue();

如果涉及到負數價格

# 佔位符 ,有數字顯示,沒有數字 爲空。不包含 0;
0 佔位符 ,有數字顯示,沒有數字 默認爲 0;

public static String formatPrice(Long price) {
     Optional<Long> price1 = Optional.ofNullable(price);
    return price1.map((Long price2) -> {
        DecimalFormat nf = new DecimalFormat("###,##0.00");
        String priceStr = nf.format((double) (price) / 100);
        return priceStr;
    }).orElse(OrderResponseCode.FORMAT_PRICE_ISNULL.getMsg());
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章