--If you want to convert (have to) convert from double to BigDecimal class, use the valueOf
method.
--Due to the nature of double, the problem of error is unavoidable, so be careful.
jdk 1.8.0_102 macOS Sierra 10.12.4
Java
double d = 0.1;
//code(1)
BigDecimal bd1 = new BigDecimal(d);
System.out.println(bd1.toPlainString());
// 0.1000000000000000055511151231257827021181583404541015625
//code(2)
BigDecimal bd2 = new BigDecimal(Double.toString(d));
System.out.println(bd2.toPlainString());
// 0.1
//code(3)
BigDecimal bd3 = BigDecimal.valueOf(d);
System.out.println(bd3.toPlainString());
// 0.1
//code(4)
BigDecimal bd4 = new BigDecimal("1.0000000000000003");
System.out.println(bd4.toPlainString());
// 1.0000000000000003
//code(5)
double d2 = 1.0000000000000003;
BigDecimal bd5 = BigDecimal.valueOf(d2);
System.out.println(bd5.toPlainString());
// 1.0000000000000002
--As in code (1), when you instantiate with the BigDecimal (double)
constructor, ** in many cases there will be an error and you will not get the expected results. ** **
--You can get the exact value by generating it from a string using the BigDecimal (String)
constructor, as in code (4).
--The BigDecimal (Double.toString (double))
method in code (2) and the BigDecimal.valueOf (double)
method in code (3) will give you "almost" expected results. (See below)
--The valueOf method may be cached and the instance may be reused. That is, depending on the value to be handled, the code (3) ** BigDecimal.valueOf (double)
may be more efficient ** than the code (2) BigDecimal (Double.toString (double))
.
So the valueOf method is the best way to convert from a double to a BigDecimal class. Including the number wrapper class, you should remember "valueOf when it comes to converting number objects".
By the way, bugs caused by using BigDecimal (double)
can be detected by the static code analysis tool FindBugs.
Not all decimal numbers (real numbers) can be represented as a Java double-like floating point property. Due to this, as in code (5), an error may be unavoidable when it is stored in double before conversion to BigDecimal.
Therefore,
--In principle, the value calculated by BigDecimal should not be stored in double during the processing process. --If you need to convert from double to Big Decimal, round it (after deciding the appropriate specifications).
So, you need to be careful.
https://docs.oracle.com/javase/jp/6/api/java/math/BigDecimal.html#BigDecimal(double)
https://docs.oracle.com/javase/jp/6/api/java/math/BigDecimal.html#valueOf(double)
http://dangerous-animal141.hatenablog.com/entry/2014/05/10/000000
http://kyon-mm.hatenablog.com/entry/20101116/1289885313
Recommended Posts