1. 程式人生 > >金額轉換為自定義字符串

金額轉換為自定義字符串

cat str integer parse ont set red ext log

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;



public final class AmountUtil {
    private static DecimalFormat LIMIT_AMOUNT_FORMAT = new DecimalFormat("#.00");

    static {
        LIMIT_AMOUNT_FORMAT.setRoundingMode(RoundingMode.FLOOR);
    }

    /**
* 1億 */ private static final int HUNDRED_MILLION = 100000000; /** * 1萬 */ private static final int TEN_THOUSAND = 10000; /** * 金額轉換為自定義字符串(保留兩位小數) */ public static String CustomFormatWith2Digits(int amount) { if (0 < amount && amount < TEN_THOUSAND) {
return String.format("%d元", amount); } else if (TEN_THOUSAND <= amount && amount < HUNDRED_MILLION) { if (amount % TEN_THOUSAND == 0) { return String.format("%d萬元", amount / TEN_THOUSAND); } else { BigDecimal tmpAmount = BigDecimal.valueOf(amount * 1.0 / TEN_THOUSAND);
return String.format("%s萬元", LIMIT_AMOUNT_FORMAT.format(tmpAmount)); } } else if (HUNDRED_MILLION <= amount) { if (amount % HUNDRED_MILLION == 0) { return String.format("%d億元", amount / HUNDRED_MILLION); } else { BigDecimal tmpAmount = BigDecimal.valueOf(amount * 1.0 / HUNDRED_MILLION); return String.format("%s億元", LIMIT_AMOUNT_FORMAT.format(tmpAmount)); } } return ""; } /** * 金額字符串(可能帶千分位)轉換為自定義字符串(保留兩位小數) */ public static String CustomFormatWith2Digits(String amountStr) { int amount = 0; try { if (amountStr.contains(",")) { amountStr = amountStr.replace(",", ""); } amount = Integer.parseInt(amountStr); } catch (NumberFormatException e) { return ""; } return CustomFormatWith2Digits(amount); } }

金額轉換為自定義字符串