Scenario Description
When doing the actual project, because uses the valueof of the double class to obtain the amount parameter which the string type saves, when needs to convert to divides into the unit namely the Shaping representation (The integer class represents), needs to use the previously obtained double data to multiply 100, Forces it to be converted to data of type int. However, the result may be a penny error, this will be a big bug, the following simulated the phenomenon of the problem and put forward a solution to the problem.
1, the string type of data is converted by double.valueof (param) multiplied by an integer, so that exactly its decimal point after the numeric value is all 0, but there will be a precision problem
String amt = "4385.73"; SYSTEM.OUT.PRINTLN (the value after the String type value is converted to a value of type Double is: "+ double.valueof (AMT)); // 4385.73 Double amount = double.valueof (AMT) *; System.out.println ("String type value is converted to a value of type Double after a value of =========" + (int) (double.valueof (AMT) * 100)); // 438572 // 438572.99999999994 String amountstr = string.valueof (Amount.intvalue ()); SYSTEM.OUT.PRINTLN (The value of the "double type value is converted to a string type value is:" + amountstr); // 438572
2, the solution, use the BigDecimal class instead of the double class to solve the amount conversion accuracy problem
String amt = "4385.73" ; BigDecimal BD =new BigDecimal (AMT); // Set the number of decimal digits, the first variable is the number of decimal digits, the second variable is the trade-off method (rounding) bd=bd.multiply ( new BigDecimal). Setscale (0 amt of BigDecimal: "+ BD); // 438573 // Convert to string output String outstring=bd.tostring (); System.out.println ( "Amt of String:" + outstring); // 438573 System.out.println ("Amt of int:" + bd.intvalue ()); // 438573
String to double error