In Java, if you need an accurate calculation answer, avoid using double type and float type

Source: Internet
Author: User

The double type and float type are primarily designed for use in scientific and engineering calculations and are used for binary floating-point calculations. For the general calculation is usually inaccurate results, so for the ordinary floating-point addition and subtraction, the solution needs to use Int,long,bigdecimal to calculate.

1. Calculate the problem?

The calculation results are as follows:

Obviously the result is not what we need. The result we need is: 0.88

So, our program should write this:

1      Public Static void Main (string[] args) {2         BigDecimal a=bigdecimal.valueof (1.29); 3         BigDecimal b=bigdecimal.valueof (0.41); 4         System.out.println (a.subtract (b)); 5     }

The final result is also the result we need:

This is a long time to see ...

  

In Java, if you need an accurate calculation answer, avoid using double type and float type

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.