java——double数据精度问题
Posted tpf386
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java——double数据精度问题相关的知识,希望对你有一定的参考价值。
代码:使用BigDecimal来代替double
public class BigDecimalUtil public static BigDecimal add(double v1,double v2) BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.add(b2); public static BigDecimal sub(double v1,double v2) BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.subtract(b2); public static BigDecimal mul(double v1,double v2) BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.multiply(b2); public static BigDecimal div(double v1,double v2) BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.divide(b2,2,BigDecimal.ROUND_HALF_UP);//四舍五入,保留2位小数
double测试示例:
public class BigDecimalTest @test public void test1() System.out.println(0.05+0.01); System.out.println(1.0-0.42); System.out.println(4.015*100); System.out.println(123.3/100);
//运行结果
//0.060000000000005
//0.57000000000000001
//401.499999999999994
//1.2329999999999999
以上是关于java——double数据精度问题的主要内容,如果未能解决你的问题,请参考以下文章