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;
}
}
The java. lang. Float. longValue() method returns value of this Float as a long (by casting to type long).
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With