I would like to increase my float
value to the first multiple of 0.5 after it.
For example, if I have: float x = 3.397;
I would like it to become: x = 3.5;
. Or, if I have: float x = 7.895;
it should become x = 8.0;
.
I would like to increase my float
value to the first multiple of 0.5 after it.
For example, if I have: float x = 3.397;
I would like it to become: x = 3.5;
. Or, if I have: float x = 7.895;
it should become x = 8.0;
.
Quite simple, but in every detail errors are hidden.
float nextHalf(float x) {
// CORRECTED THIS: long n = Math.round(x * 2.0) + 1;
return (float) (Math.ceil(x * 2.0) / 2);
}
With corrections due to @chux-ReinstateMonica.
As rounding methods round/floor/ceil target integer units of 1, for 0.5 one must first scale the numbers by a factor 2 and afterwards divide by 2.
Of course because of the incorporated exponent in a floating point number at some large numbers the difference between successive numbers is no longer below 1.0 so then
nextHalf(x) == nextHalf(x + 1.0)