The calculation of large numerical value in Java

Source: Internet
Author: User

I believe that everyone may encounter to the value of more than 17-bit integer, Java in the value of double is more than 8 bits will become a scientific notation, so I used the DecimalFormat format, when the pattern is "#################.##", The value of "123456789012345.78" can be displayed normally, not formatted with 1.2345678901234578E14 formatted 123456789012345.78 but the value of more than 15-bit integer case is not the same, such as the value of " 1234567890123456.78 "After the format is 1234567890123456.8, has been rounded up." Finally checked Javadoc, found in the Java.math package has a class of bigdecimal can solve the problem of large numerical calculation, is quite good, and finally solved the problem.

Example://Test BigDecimal

BigDecimal bd=new BigDecimal ("12345678901234578.789");

SYSTEM.OUT.PRINTLN ("BigDecimal * 12.5=" + (bd=bd.multiply (new BigDecimal (12.5)));

System.out.println ("bigdecimal/12.5=" +bd.divide (New BigDecimal (12.5));

Output is: BigDecimal * 12.5=154320986265432234.8625

bigdecimal/12.5=12345678901234578.789

Absolutely right!

Attention: BigDecimal when used to pay attention to it in the form of internal representation of the computer, the new BigDecimal (double) This constructor generated BigDecimal class will become unpredictable, because the 0.100000000******* To represent 0.1, and use 0.29999999***** to indicate that if you do not process the results, there may be bugs.

Related Article

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.