Java数字转化为单位为万或亿

wylc123 9天前 ⋅ 17 阅读
    public static String formatNumberWithUnit(String needFormatNumber) {
        final String noNumDefaultValue = "0";
        if (!NumberUtils.isNumber(needFormatNumber)) {
            return noNumDefaultValue;
        }
 
        String nuit = "",formatNumStr = "";
        StringBuffer sb = new StringBuffer();
        BigDecimal b1 = new BigDecimal("10000");
        BigDecimal b2 = new BigDecimal("100000000");
        BigDecimal needNum = new BigDecimal(needFormatNumber);
 
        if (needNum.compareTo(b1) == -1) {
            sb.append(needNum.toString());
        }
        // 以万为单位处理
        else if ((needNum.compareTo(b1) == 0 || needNum.compareTo(b1) == 1) && needNum.compareTo(b2) == -1) {
            formatNumStr = needNum.divide(b1).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
            nuit = "万";
        }
        // 以亿为单位处理
        else if (needNum.compareTo(b2) == 0 || needNum.compareTo(b2) == 1) {
            formatNumStr = needNum.divide(b2).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
            nuit = "亿";
        }
 
        if (StringUtils.isNotBlank(formatNumStr)) {
            sb.append(showAmountHandle(formatNumStr)).append(nuit);
        }
 
        if (sb.length() == 0) {
            return noNumDefaultValue;
        }
 
        return sb.toString();
    }
 
    public static String showAmountHandle(String finishedCount) {
        if (StringUtils.isBlank(finishedCount)) {
            return BigDecimal.ZERO.toString();
        }
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        return String.valueOf(nf.format(new BigDecimal(finishedCount).doubleValue()));
    }

全部评论: 0

    我有话说: