在项目中需要统计各个商品的价格。出现结果丢失问题。如下
问题代码
@Test
void contextLoads4() throws Exception{
double a = 3.3;
double b = 6.6;
double c = 1.1;
double d = 0.0;
ArrayList<Double> arrayList = new ArrayList();
arrayList.add(a);
arrayList.add(b);
arrayList.add(c);
arrayList.add(d);
Double f = 0.0;
for (Double p : arrayList) {
f +=p;
}
System.out.println("f = " + f);
}
结果:
此结果明显不是我们想要的
解决办法:将double类转为BigDecimal 在相加
@Test
void contextLoads5() throws Exception{
double a = 3.3;
double b = 6.6;
double c = 1.1;
double d = 0.0;
ArrayList<BigDecimal> arrayList = new ArrayList<>();
arrayList.add(BigDecimal.valueOf(a));
arrayList.add(BigDecimal.valueOf(b));
arrayList.add(BigDecimal.valueOf(c));
arrayList.add(BigDecimal.valueOf(d));
BigDecimal f = BigDecimal.ZERO;
for (BigDecimal p : arrayList) {
f = f.add(p);
}
System.out.println("f = " + f);
System.out.println("f.doubleValue() = " + f.doubleValue());
}
结果正确