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