Logo

Programming-Idioms

  • Dart
  • Java
  • Java
  • Go
  • C++

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

int y = static_cast<int>(x);
int y = x.toInt()

There is no automatic conversion, so you have to explicitly call toInt on the double. The toInt call truncates, there are also ceil, floor and round methods.
int y = (int)x;
y := int(x)
Y : constant Integer := Integer (Float'Truncation (X));

New implementation...