In the process of writing the code today, when a variable of double is converted to BigDecimal by new BigDecimal (double D), the valid number is changed, as follows:
public class Bigdecimaltest { public static void main (string[] arg) {String S1 = "123.45" ; Double D1 = new double (S1);
Construct BigDecimal BigDecimal bg1 = new BigDecimal (D1);
//Use a double type of parameter construction BigDecimal BigDecimal bg2 = new BigDecimal (S1); System.out.println ( bg1 = "+bg1"); System.out.println ( bg2 = "+bg2"); }}
Output:
BG1 = 123.4500000000000028421709430404007434844970703125
Bg2 = 123.45
Double numbers of the same size, the same precision can be obtained by constructing the BigDecimal in the form of a string parameter. Using a double construct can result in a change in precision. In fact, according to the official API documentation, it is recommended to convert float, double to biddecimal using the string parameter, the original document: For values other than float double and NaN and±infinity, This constructor was compatible with the values returned by Float.toString(float) and Double.toString(double) . This is generally the preferred-to convert a float or into double a BigDecimal, as it doesn ' t suffer from the unpredict Ability of the BigDecimal(double) constructor. more than that, the following are also true:
Public classBigdecimaltest { Public Static voidMain (string[] arg) {String S1= "123.45"; String S2= "123.450"; Double D1=NewDouble (S1); Double D2=NewDouble (S2); BigDecimal bg1=NewBigDecimal (S1); BigDecimal Bg2=NewBigDecimal (S2); System.out.println ("D1.equals (D2):" +d1.equals (D2)); System.out.println ("Bg1.equals (BG2):" +bg1.equals (BG2)); }}
Output:
D1.equals (D2): True
Bg1.equals (BG2): false
Decimals of the same size, valid numbers in different cases, the size of the double type is equal to the result of our actual calculation. However, they are converted into bigdecimal and then compared to the size, resulting in unequal results.
The conversion of double and BigDecimal in Java