Logo

Programming-Idioms

  • Haskell
  • Java

Idiom #81 Round floating point number to integer

Declare the integer y and initialize it with the rounded value of the floating point number x .
Ties (when the fractional part of x is exactly .5) must be rounded up (to positive infinity).

import static java.lang.Integer.parseInt;
import static java.math.RoundingMode.HALF_UP;
import static java.text.NumberFormat.getNumberInstance;
NumberFormat f = getNumberInstance();
f.setRoundingMode(HALF_UP);
f.setMaximumFractionDigits(0);
int y = parseInt(f.format(x));
long y = Math.round(x);

Math.round() converts a float to an int, or a double to a long.
y = floor (x + 1/2)

Haskell would round half-ties towards nearest ∈ℤ2 rather than towards +∞
Y : constant Integer := Integer (Float'Rounding (X));

New implementation...