1

I'm fairly new to java but have some experience of coding (mostly PHP and some C++).

I'm having some trouble with calculations in my program. When I run the following code:

public class Test {

    public static void main(String[] args) {
        double number = 2 - (0.10 + 1.05);
        System.out.println( number );

        if( number < 0.85 ) System.out.println("to small");

    }
}

My output is as follows:

run:
0.8499999999999999
to small
BUILD SUCCESSFUL (total time: 0 seconds)

I'm expecting 2 - ( 0.10 + 1.05 ) to be equal to 0.85 but for some reason it's not. Does anyone know why it would behave like this?

I'm using netbeans to code version 7.3.1 and jdk7u25 on Windows 8 if that is important. If there is anything else I should add please tell.

/Chris

Christian Eriksson
  • 2,038
  • 2
  • 22
  • 28

3 Answers3

4

That is because floating point numbers cannot represent all numbers in its range precisely, but takes something close. See:

http://introcs.cs.princeton.edu/java/91float/

That is also why you should never use float or double for storing monetary values.

Xabster
  • 3,710
  • 15
  • 21
2

Floating points numbers are in exponential form. There consists of mantissa and exponent field. Because of binary coding they do not cover exact numbers, but are close to them.

To have exact numbers use BigDecimal - http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html .

Pawel
  • 1,457
  • 1
  • 11
  • 22
0

Because floating point numbers don't work like you think they do. In a nutshell, not all numbers can be precisely expressed in floating-point format, so you will see things like this when you use floating point data types.

DUman
  • 2,560
  • 13
  • 16