Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java int cast returns 0

Tags:

java

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?)

like image 685
Luke Taylor Avatar asked Dec 21 '12 09:12

Luke Taylor


People also ask

Can integer be cast to number Java?

You can't cast from int to Number because int is a primitive type and Number is an object. Casting an object is changing the reference type from one type of object to another.

How do I cast a value to an int?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

Can we cast int to byte?

An int value can be converted into bytes by using the method int. to_bytes().


2 Answers

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
like image 40
Abubakkar Avatar answered Sep 22 '22 15:09

Abubakkar


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.

like image 139
cowls Avatar answered Sep 21 '22 15:09

cowls