double保留两位小数

文章目录

  • 返回类型为double(四舍五入)
  • 返回类型是 String【需要去除末尾多余0的,请看第4点】

我们都知道double和float都是浮点型,在转型或者比较的时候可能出现问题,这里讲一下怎么针对double类型做精度处理

返回类型为double(四舍五入)

  1. 使用Math.round转成long再转回double
        double dou = 3.1487426;
        dou = (double) Math.round(dou * 100) / 100;   
        System.out.println(dou);
  1. 使用BigDecimal进行格式化
        double dou = 3.1487426;
        BigDecimal bigDecimal = new BigDecimal(dou).setScale(2, RoundingMode.HALF_UP);
        double newDouble = bigDecimal.doubleValue();
        System.out.println(newDouble);

返回类型是 String【需要去除末尾多余0的,请看第4点】

  1. 使用String.format()格式化(四舍五入)
        double dou = 3.1487426;
        String douStr = String.format("%.2f", dou)
        System.out.println(douStr);
  1. 使用NumberFormat进行格式化(四舍五入)
        double dou = 3.1487426;
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setMaximumFractionDigits(2);
        // numberFormat.setRoundingMode(RoundingMode.UP);  //默认的模式就是四舍五入,可以省略
        String douStr = numberFormat.format(dou)
        System.out.println(douStr);
  1. 使用BigDecimal进行格式化(四舍五入)
        double dou = 3.1487426;
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        String str = decimalFormat.format(dou);
        System.out.println(str);
  1. 去除末尾多余的 0
	 /**
     * 方式一:格式化数值(四舍五入),去除末尾无效的0
     *
     * @param value 值
     * @param scale 保留小数位数
     * @return
     */
    public static String scaleTrimZero(Double value, int scale) {
        if (Objects.isNull(value)) {
            return "";
        }
        // 使用 stripTrailingZeros() 会变成科学计数法,需要使用 toPlainString() 转字符串
        return BigDecimal.valueOf(value).setScale(scale, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
    }
    
    /**
     * 方式二:格式化数值(四舍五入),去除末尾无效的0
     *
     * @param value 值
     * @param scale 保留小数位数
     * @return
     */
    public static String scaleTrimZero(Double value, int scale) {
        if (Objects.isNull(value)) {
            return "";
        }
        BigDecimal bigDecimal = BigDecimal.valueOf(value).setScale(scale, RoundingMode.HALF_UP);
        String str = bigDecimal.toString();
        if (str.contains(".")) {
            str = str.replaceAll("0+$", "");
            str = str.replaceAll("[.]$", "");
        }
        return str;
    }

你可能感兴趣的:(Java,基础,java)