java常用工具方法

double类型后补0

private String roundByScale(double v, int scale) {
    if (scale < 0) {
        throw new IllegalArgumentException(
                "The   scale   must   be   a   positive   integer   or   zero");
    }
    if(scale == 0){
        return new DecimalFormat("0").format(v);
    }
    String formatStr = "0.";
    for(int i = 0; i < scale; i++){
        formatStr = formatStr + "0";
    }
    return new DecimalFormat(formatStr).format(v);
}

数字过万/亿自动换算成以万/亿为单位

    private static final String MILLION_UNIT = "万";
    private static final String BILLION_UNIT = "亿";
    private static final BigDecimal ONE_HUNDRED_THOUSAND = new BigDecimal(10000);
    private static final BigDecimal ONE_HUNDRED_MILLION = new BigDecimal(100000000);
    private static final BigDecimal TEN_THOUSAND = new BigDecimal(10000);
    
    /**
     * 数字过万/亿自动换算成以万/亿为单位
     * @param var 待转换参数
     * @param scale 保留位数
     * @return
     */
    public static String amountConversion(String var, @Nullable Integer scale) {
        // 参数校验
        Assert.notNull(var, "The var cannot be empty");
        Pattern pattern = Pattern.compile("(^[+-]?[0-9]+)|(^[+-]?[0-9]+\\.[0-9]+)");
        if (!pattern.matcher(var).matches()) {
            throw new IllegalArgumentException("var must be number");
        }

        BigDecimal amount = new BigDecimal(var);
        if (scale == null) {
            scale = CommonConstant.FOUR_SCALE;
        }

        if (amount.abs().compareTo(ONE_HUNDRED_THOUSAND) < 0) {
            //如果小于1万
            return amount.stripTrailingZeros().toPlainString();
        }
        if (amount.abs().compareTo(ONE_HUNDRED_MILLION) < 0) {
            //如果大于1万小于1亿
            return amount.divide(TEN_THOUSAND, scale, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString() + MILLION_UNIT;
        }
        return amount.divide(ONE_HUNDRED_MILLION, scale, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString() + BILLION_UNIT;
    }

java除法保留n位小数,默认保留2位小数

/**
     *
     * @param var1 被除数
     * @param var2 除数
     * @param scale 小数点保留为数
     * @return
     */
    public static String computeDivision(String var1, String var2, @Nullable Integer scale) {
        Assert.notNull(var1, "The dividend cannot be empty");
        Assert.notNull(var2, "The divisor cannot be empty");
        if ("0".equals(var2)) {
            throw new ArithmeticException("The divisor cannot be zero");
        }
        if (scale == null) {
            scale = 2;
        }
        BigDecimal result = new BigDecimal(var1).divide(new BigDecimal(var2), scale, RoundingMode.HALF_UP);
        return result.toString();
    }
posted @ 2022-11-16 09:02  道之缘  阅读(8)  评论(0编辑  收藏  举报