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());
}