I have the following piece of code:
public static final long KILOMETER_IN_METERS = 1000;
public static int getKilometers(int distanceInMeter) {
return (int) Math.floor(distanceInMeter / KILOMETER_IN_METERS);
}
And for the line with the return statement Sonar says:
Integral division result cast to double or float
Here is the full description of this bug.
As far as I understand, it says there is int/int division whose result could be a floating value, but I could be wrong.
How can I handle this case correctly?
There is no need to use Math.floor
here. Math.floor
is an operation on double
, and it does nothing when you supply an int to it.
Returns the largest (closest to positive infinity)
double
value that is less than or equal to the argument and is equal to a mathematical integer. Special cases:
- If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
- If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.
(Source)
The integer division already has the same logical behavior of Math.floor
, i.e. it truncates the remainder of the division operation. int/int
always returns an int
.
For example, 100/3
would return 33
, and 40/50
would return 0
.
Simply use this code :
public static int getKilometers(int distanceInMeter) {
return distanceInMeter / KILOMETER_IN_METERS;
}