码迷,mamicode.com
首页 > 编程语言 > 详细

java——double数据精度问题

时间:2019-07-12 12:44:49      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:VID   double   col   oid   代码   小数   print   rac   结果   

代码:使用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数据精度问题

标签:VID   double   col   oid   代码   小数   print   rac   结果   

原文地址:https://www.cnblogs.com/Tpf386/p/11175384.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!