String to double error

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.