Java glitch? Subtraction of numbers?

Is this a bug in Java?

I solve this expression: 3.1 - 7.1

I get an answer: -3.9999999999999996

What's going on here?

+5
source share
5 answers

A great explanation can be found here. http://www.ibm.com/developerworks/java/library/j-jtp0114/

. , 0,5, ( 2) ( 0,5 2-1), , 0,1, . , , - - , . , 2.600000000000001, 2.6:

double s=0;

for (int i=0; i<26; i++)
    s += 0.1;
System.out.println(s); 

, .1 * 26 , .1 26 . , , "", . , :

  double d = 29.0 * 0.01;
  System.out.println(d);
  System.out.println((int) (d * 100));

:

 0.29
  28  

, , , .

. .

+10

, double, , . . BigDecimal:

BigDecimal a = new BigDecimal("3.1");
BigDecimal b = new BigDecimal("7.1");
BigDecimal result = a.subtract(b);
System.out.println(result);      // Prints -4.0
+2

100%, , - . Java can not , , , !

P.S. Google,

+1

same as 3 * 0.1 != 0.3(if it is not compiled by the compiler at least)

+1
source

Automatic type promotion occurs, and this is the result.

Here is some resource to learn.

http://docs.oracle.com/javase/specs/jls/se5.0/html/conversions.html

The next step is to learn how to use formatter to format them with the given accuracy / requirements.

+1
source

All Articles