规则3-数字-10条-不要使用BigDecimal对象构造浮点数据

因为浮点数字总是不准确的, 通过 new BigDecimal(double) 获取到的数据总是不准确的。

1
2
3
4
5
6
// Prints 0.1000000000000000055511151231257827021181583404541015625
// when run in FP-strict mode
double d = 1.1;
BigDecimal bd1 = new BigDecimal(d); // Noncompliant; see comment above
BigDecimal bd2 = new BigDecimal(1.1); // Noncompliant; same result
System.out.println(String.format("bd1 %s bd2%s ",bd1,bd2));
  • 通过 BigDecimal.valueOf能准确获取到数值。
  • 通过字符串类型能够获取到准确的十进制数据。
1
2
3
4
5
6
double d = 1.1;

BigDecimal bd1 = BigDecimal.valueOf(d);
BigDecimal bd2 = new BigDecimal("1.1"); // using String constructor will result in precise value
System.out.println(String.format("bd1 %s bd2%s ",bd1,bd2));

参考

文章目录