Java使用BigDecimal解决浮点型运算丢失精度的问题
-
@Test public void test1(){ System.out.print(0.05+0.01); }
-
@Test public void test2(){ BigDecimal b1 = new BigDecimal(0.01); BigDecimal b2 = new BigDecimal(0.05); System.out.print(b1.add(b2)); }
-
@Test public void test3(){ BigDecimal b1 = new BigDecimal("0.01"); BigDecimal b2 = new BigDecimal("0.05"); System.out.print(b1.add(b2)); }
- BigDecimal的加减乘除的工具类
package com.mmall.util; import java.math.BigDecimal; public class BigDecimalUtil { private 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);//四舍五入,保留两位小数 } }
杂家不如专家,精益求精