java:Integer类型相除求百分比,并实现double保留两位小数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38750084/article/details/86990647

       

Format format=new DecimalFormat("0.000");
        System.out.println("format==="+format.format((double)34/54));
        
        //保留两位小数并四舍五入
        double d0 = 114.145123;
        DecimalFormat df0 = new DecimalFormat("#.00");
        String str = df0.format(d0);
        System.out.println("d0str==="+str);



或者用以下方法保留两位小数:

/**
     * 提供精确的小数位四舍五入处理。
     *
     * @param v 需要四舍五入的数字
     * @param scale 小数点后保留几位
     * @return 四舍五入后的结果
     */
    public static double round(double v, int scale) {
        //System.out.println("v=="+v);
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

运行结果:

format===0.630
d0str===114.14

猜你喜欢

转载自blog.csdn.net/weixin_38750084/article/details/86990647