金额转换为自定义字符串

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

 

转载于:https://www.cnblogs.com/zhshlimi/p/7808766.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值