Add floating-point numbers in Java

Source: Internet
Author: User

Today encountered a more interesting question, that is, two floating-point number add how can not get the correct answer, just start also very puzzled, later through on-line to find information, understand the original floating point with 2 to add and subtract words really will appear this situation, also found the solution, so record down, is a more interesting understanding of it!

First, let's take a look at two floating-point numbers with decimals.

Package Com.controller;public class Test {public static void main (string[] args) {//TODO auto-generated method stub        D Ouble a = 418.48d;        Double b = 7121.88d;        Double c = a+b;        System.out.println (c);}}

The output result is

7540.360000000001

The reason is that the binary phase of the floating-point calculation will have a certain error, the reason we go further into the next step, we look at the solution

Package Com.controller;import Java.math.bigdecimal;public class Test {public static void main (string[] args) {//TODO Auto -generated method Stub        Double A = 418.48d;        Double b = 7121.88d;        BigDecimal A1 = new BigDecimal (string.valueof (a));        BigDecimal B1 = new BigDecimal (string.valueof (b));        BigDecimal C = A1.add (B1);        System.out.println (C.doublevalue ());}}

The output result is

7540.36

  

 

Add floating-point numbers in Java

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.