Logo

Programming-Idioms

  • Lisp
  • C++
  • PHP
  • Java

Idiom #80 Truncate floating point number to integer

Declare integer y and initialize it with the value of floating point number x . Ignore non-integer digits of x .
Make sure to truncate towards zero: a negative x must yield the closest greater integer (not lesser).

y = int(x)
(truncate x)

; You might also define it using floor function:
(defun tr (x)
(let ((fl (floor x)))
(if (and (< x 0) (> x fl)) (+ 1 fl) fl ))
)
int y = static_cast<int>(x);
$y = (int)$x;
int y = (int)x;
Y : constant Integer := Integer (Float'Truncation (X));

New implementation...