5

I have the following code:

int i = (int) 0.72;
System.out.println(i);

Which yields the following output:

0

I would of imagined that the variable i should have the value of 1 (since 0.72 > 0.5 => 1), why is this not the case?

(I imagine that when casting to int, it simply cuts of the decimal digits after the comma, not taking into account of rounding up; so I'll probably have to take care of that myself?)

Luke Taylor
  • 9,481
  • 13
  • 41
  • 73

7 Answers7

7

Correct, casting to an int will just truncate the number. You can do something like this to get the result you are after:

int i = (int)Math.round(0.72);
System.out.println(i);

This will print 1 for 0.72 and 0 for 0.28 for example.

cowls
  • 24,013
  • 8
  • 48
  • 78
3

Because when you cast a double to int, decimal part is truncated

UPDATE Math.round will give your desired output instead of Math.ceil:

 System.out.println(Math.round(0.72));
// will output 1

 System.out.println(Math.round(0.20));
// will output 0

You can use Math.ceil :

System.out.println(Math.ceil(0.72));
// will output 1
 System.out.println(Math.ceil(0.20));
// will output 1
Abubakkar
  • 15,488
  • 8
  • 55
  • 83
1

Casting to an int implicity drops the decimal part. That's why you get 0 because anything after the 0 is removed (in your case the 72). If you want to round then look at Math.round(...)

RNJ
  • 15,272
  • 18
  • 86
  • 131
1

Explicit cast does a conversion a float/double value to an int variable (which discards the fractional part)

S Kr
  • 1,831
  • 2
  • 25
  • 50
1

Java does not round-off the number like we do.It simply truncates the decimal part. If you want to round-off the number use java.lang.Math

Shurmajee
  • 1,027
  • 3
  • 12
  • 35
1

Casting double to int truncates the non-integer portion of the number.

To round numbers as you describe, use Math.round()

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

As a complete Java beginner, and just in case my experience is useful to someone, I was just making the following mistake:

int x = (int) Math.random() * 10;

... which will always set x to 0. Instead, I should've done int x = (int) (Math.random() * 10);.

Not much of a Java-know-how specific mistake, but I'll just throw this in case anyone puzzled by this stumbles upon this question.