FormatUtil: Correctly fix the Math#round() error flagged by error-prone

The fix applied by I1c88102d4 got rid of the error-prone warning but
missed to address the actual issue in that line of code. The intention
of the original code was to compute a double/float percentage and
mathematically round it to the next integer/long value. However, as
(long * int / long) == long, the computed percentage was a long value,
for which the floor operation was automatically applied. Hence, the
round function was even meaningless. The correct fix is to use a double
value in the operation so that the result is also of type double and
preserves all fractions.

By doing so, we also get rid of the error-prone warning, which only
indirectly hinted at that error.

Change-Id: Iea07a05281faf00b0b52cf25a2fd35ca25b069c5
This commit is contained in:
Alice Kober-Sotzek 2018-09-14 14:11:40 +02:00
parent 650df0f7be
commit 879d7cf6a5

View File

@ -137,25 +137,7 @@ public class FormatUtil {
if (size == 0) {
return Resources.C.notAvailable();
}
int p = Math.abs(saturatedCast(delta * 100 / size));
return p + "%";
}
/**
* Returns the {@code int} nearest in value to {@code value}.
*
* @param value any {@code long} value
* @return the same value cast to {@code int} if it is in the range of the {@code int} type,
* {@link Integer#MAX_VALUE} if it is too large, or {@link Integer#MIN_VALUE} if it is too
* small
*/
private static int saturatedCast(long value) {
if (value > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (value < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int) value;
long percentage = Math.abs(Math.round(delta * 100.0 / size));
return percentage + "%";
}
}