Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

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).

Y : constant Integer := Integer (Float'Rounding (X));
#include <math.h>
int y = (int)floorf(x + 0.5f);
(defn rnd [y] (int (+ y 0.5)))
#include <cmath>
int y = static_cast<int>(std::floor(x + 0.5f));
using System;
long y = (long)Math.Round(x);
import std.math: round;
int y = cast(int) x.round;
var y = x.round();
y = Kernel.round x
integer :: y

y = nint(x)
import "math"
y := int(math.Floor(x + 0.5))
y = floor (x + 1/2)
var y = Math.round(x);
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);
(defun rnd (y) (floor (+ y 0.5)))
function round(float)
    local int, part = math.modf(float)
    if float == math.abs(float) and part >= .5 then return int+1    -- positive float
    elseif part <= -.5 then return int-1                            -- negative float
    end
    return int
end
function round(float)
    return math.floor(float + .5)
end
$y = (int) round($x);
var
  y: integer;
  x: double;
begin
  y := round(x);
end.
my $y = int($x + 1/2);
y = int(x + 0.5)
y = (x + 1/2r).floor
let y = x.round() as i64;
(define y (round x))

New implementation...