当前位置:编程学习 > JAVA >>

java保留两位小数,四舍五入

看代码。
DecimalFormat df = new DecimalFormat("#.00");
double d = 63*0.105;
        System.out.println(d);
        System.out.println(df.format(d));
        System.out.println(String.format("%.2f", d));

这边这个d只能用double型。。63*0.015应该为6.615 但是变为了6.61499999。。。怎么破 --------------------编程问答--------------------
public class Hello {
    public static double numberWithPrecision(double value, int precision) {
        double temp = Math.pow(10, precision);
        return ((int) Math.round(temp * value)) / temp;
    }

    public static void main(String[] args) {
        System.out.println(Hello.numberWithPrecision(6.615, 2));
    }
}
--------------------编程问答-------------------- http://www.java3z.com/cwbwebhome/article/article8/855.html --------------------编程问答--------------------
引用 1 楼 Inhibitory 的回复:
public class Hello {
    public static double numberWithPrecision(double value, int precision) {
        double temp = Math.pow(10, precision);
        return ((int) Math.round(temp * value)) / temp;
    }

    public static void main(String[] args) {
        System.out.println(Hello.numberWithPrecision(6.615, 2));
    }
}


学习 --------------------编程问答-------------------- --------------------编程问答-------------------- 给你一个最基本的数据类型转换
                  double d=63*0.105;
                double a=(d*1000+0.5);
int b=(int)a;
float c=b/1000f;
System.out.println(c); --------------------编程问答--------------------
引用 1 楼 Inhibitory 的回复:
public class Hello {
    public static double numberWithPrecision(double value, int precision) {
        double temp = Math.pow(10, precision);
        return ((int) Math.round(temp * value)) / temp;
    }

    public static void main(String[] args) {
        System.out.println(Hello.numberWithPrecision(6.615, 2));
    }
}

+1 --------------------编程问答-------------------- 关于类似问题原理都一样:
都是先给他乘个10或者100,或者1000等等,根据你保留的小数位数有关系,然后在根据结果处于相应的那个乘数。就得到你想要的值了! --------------------编程问答-------------------- 遇到这种加减乘除,四舍五入,保留几位的问题,我都是用BigDecimal类的setScale(n, RoundingMode.HALF_UP)方法。保留小数点几位,后面一个参数是四舍五入的模式。 --------------------编程问答-------------------- public static double round(double v, int scale) {
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();
}
补充:Java ,  Web 开发
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,