Precision loss in float and double subtraction operations

Source: Internet
Author: User

Precision loss occurs when the float and double types perform subtraction. This problem is mainly caused by the widespread use of binary in computers. This is a record to prevent future forgetting.

Public static void main (string [] ARGs) {float a = 2.1f; float B = 2.0f; float c = A-B; system. out. println ("a-B =" + C);} // output: A-B = 0.099999905

In this case, you need to use the bigdecimal class

Bigdecimal add (bigdecimalaugend) addition operation

Bigdecimal subtract (bigdecimal subtrahend) subtraction operation

Bigdecimal multiply (bigdecimal multiplicand) Multiplication

Bigdecimal divide (bigdecimal divisor) division operation

Public static void main (string [] ARGs) {float a = 2.1f; float B = 2.0f; bigdecimal a1 = new bigdecimal (float. tostring (a); bigdecimal b1 = new bigdecimal (float. tostring (B); float C1 = a1.subtract (B1 ). floatvalue (); system. out. println ("a1-b1 =" + C1);} // output: a1-b1 = 0.1

Detailed principle reference http://www.blogjava.net/jelver/articles/340038.html

This article is from the blog "plug on the name of pigs", please be sure to keep this source http://zuohao1990.blog.51cto.com/6057850/1560642

Precision loss in float and double subtraction operations

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.