Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java float to long Typecast

Can anyone tell me what am I doing wrong here. I am able to typecast y into long, but the same doesn't work for x/y.

class Test {

long convert(int x, float y) {
    //return (long) x/y; // cannot convert from float to long
    return (long)y;
    }

}
like image 692
ncst Avatar asked Jul 09 '13 17:07

ncst


People also ask

Can we convert float to long in Java?

The java. lang. Float. longValue() method returns value of this Float as a long (by casting to type long).

Can we convert float to double in Java?

The doubleValue() method of Java Float class returns a double value corresponding to this Float Object by widening the primitive values or in simple words by directly converting it to double via doubleValue() method .

Can a float hold a long?

The largest number a long can hold is 263 - 1. Meanwhile, a float, which is 32 bits shorter than a long, can hold up to (2-2-23)�2127. You see, any value that can be represented by a long can be approximated by a float. Therefore, if you convert a long to a float, you have no risk of losing data.


1 Answers

The only issue here is how things are parenthesized. You'd be fine if you wrote

return (long) (x / y);

When you wrote (long) x / y, that was treated as ((long) x) / y, which is a float according to the typing rules of Java.

like image 102
Louis Wasserman Avatar answered Sep 27 '22 19:09

Louis Wasserman