类似于new BigDecimal(3.1F)
或者BigDecimal.valueOf(3.1F)
会失掉精度,应该选用new BigDecimal(Float.toString(3.1F))
等方式。原因参考:https://docs.oracle.com/javase/10/docs/api/java/math/BigDecimal.html#%3Cinit%3E(double)
1,The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.
2,The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.
3, When a double must be used as a source for a BigDecimal, note that this constructor provides an exact conversion; it does not give the same result as converting the double to a String using the Double.toString(double) method and then using the BigDecimal(String) constructor. To get that result, use the static valueOf(double) method.
1, 该构造函数的接口可能是非预期的。一般会认为new BigDecimal(0.1)的值应该绝对等于0.1,但实际上是0.1000000000000000055511151231257827021181583404541015625。这是因为0.1不能用double精确的表达,真正传递给构造函数的值并不是精确的0.1。
2,String构造函数却可完美预期,new BigDecimal("0.1")会得到精确值。因此通常建议使用String构造函数。
3, 如果必须用double作为BigDecimal的原始数据,应注意该构造函数会做额外转化;所得的值和把double转成String在通过String构造函数所得值不同。要获得String构造函数所得值需要通过静态的valueOf(double)方法。
需要注意BigDecimal.valueOf(3.1F)
虽然调用了valueOf(double)方法,但是在float转double的时候就已经失真了。