Logo

Programming-Idioms

  • C
  • Java
  • PHP
  • Js

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

let y = BigInt (x | 0)

`x | 0` chops off the bit of a number after the decimal.
`BigInt`s are a new JavaScript primitive for arbitrarily large integers. They are only supported by Chrome, NodeJS, and Firefox.
int y = (int)x;

The (int) isn't really necessary. The compiler will cast x automatically.
int y = (int)x;
$y = (int)$x;
Y : constant Integer := Integer (Float'Truncation (X));

New implementation...