0

I'am confused. I'm trying to get an int value:

Integer ord = new Double(33 / (-2 * 1.1)).intValue();

Expectation: -15
Output: -14

What's wrong?

When I try:

Double d = 33 / (-2 * 1.1);

Output: -14.999999999999998

Any ideas? Thanks in advance!

Mathias Müller
  • 22,203
  • 13
  • 58
  • 75
Zanas_x3
  • 47
  • 6

6 Answers6

6

.intValue() will trunc the frarctinal part so you can use Math.ceil(), Math.floor() or you can use Math.round() to approximate it to the nearest value

Integer result = (int) Math.round(new Double(33/(-2*1.1))); //-15
Integer result = (int) Math.floor(new Double(33/(-2*1.1))); //-15
Integer result = (int) Math.ceil(new Double(33/(-2*1.1)));  //-14

You can see that Math.ceil() give us 14 because this is a negative number -14>-15 so the ceil of -14.9999 is -14 and the inverse apply on Math.floor()

Tareq Salah
  • 3,720
  • 4
  • 34
  • 48
  • 2
    It depends on what Zanas_x3 wants but I'd say `Math.round()` is probably more what he expects than `Math.ceil()`. – Jesper Jan 09 '14 at 08:13
  • Thanks! I need to trunc, because I expect such results: Integer ord = new Double(32 / (-2 * 1.1)).intValue(); //-14 Integer ord = new Double(33 / (-2 * 1.1)).intValue(); //-15 Integer ord = new Double(34 / (-2 * 1.1)).intValue(); //-15 – Zanas_x3 Jan 09 '14 at 08:41
1

intValue() doesn't do round but truncate.

gbejic
  • 302
  • 1
  • 5
1

The double output of -14.999999999999998 has it's origin in the precision of the double type. A floating point number is always a sum of 2^n numbers. The result is that not all numbers can be represented precisely, even with double.

Your integer example returns -14 because the integer value of -14.999999999999998 is -14. There is no rounding when getting the integer value. It is just cut of at the decimal point.

For rounding use either Math.ceil() for rounding up, Math.floor() for rounding down or Math.round() for general rounding.

André Stannek
  • 7,773
  • 31
  • 52
1

When getting the int value of a double, java isn't doing any round up or down for you. It just omits the decimals.

What you want to do is to use the Math.round(double) to get the value you are expecting.

I believe the java doc for Math.round() says it will return a long value, but if you are sure that your result never will be larger than the maximum int value, then you can cast it to an int.

 int result = (int) Math.round(new Double(33/(-2*1.1)));
Nadrendion
  • 247
  • 1
  • 7
0

Warning: Using the authority argument :P

Josh Bloch has an entire item in his Effective Java book against using double or float when aiming for accuracy. In my life, working with currency, for example, I have had the best results working with BigDecimal

Jorge_B
  • 9,712
  • 2
  • 17
  • 22
0

You are using 32 bit float so losing a lot of precision. Try Double d = 33 / (-2 * 1.1d); And, as everybody say, better round than truncate.

aalku
  • 2,860
  • 2
  • 23
  • 44