int

Tcl 8 and earlier versions

The expr-function int() returns the part of a number that fits in the native C long integer type. For non-integers, this means the fractional part is discarded (truncation). For numbers of large absolute value, the most significant bits are discarded, but how many are kept depends on details in how Tcl was compiled. tcl_platform(wordSize) gives the size in bytes of the native long type.

 % set tcl_platform(wordSize)
 4
 % expr int(2.3e7)
 23000000
 % expr int(2.3e8)
 230000000
 % expr int(2.3e9)
 -1994967296
 % expr int(0x70102030*2)
 -534757280
 % expr 70000*70000
 4900000000
 % expr int(70000*70000)
 605032704

Note that you can have

 % expr int(1e30)
 0

int has two companions for larger integers:

  • wide for 64-bit integers (Tcl8.4+)
  • entier (French pronounciation) for unlimited size integers (Tcl8.5+)

All of these do truncation when applied to doubles and all of them raise errors if the argument is non-finite or Not a Number (NaN):

 % expr { int(+inf) }
 integer value too large to represent
 % expr { int(-inf) }
 integer value too large to represent
 % expr { int(nan) }
 floating point value is Not a Number

Tcl 9

Behavior of int() function changed with Tcl 9 (see TIP514 ). It no longer limits the result to fit native long integer range.

Math functions wide() and entier() continue to exist but their use is deprecated.

Consider rounding

For "making an integer out of a real number", one should generally use round rather than int, because int(0.999999999) is very different from int(1.00000001). An exception to this rule of thumb is on the output of rand, where

  expr {1 + int(rand()*6)}

is really the way to "roll a dice". This is in part because the value of rand is really an integer that masquerades as a number >0 and <1.

See also

For more controlled conversion to integers there are:

  • round for proper rounding.
  • floor for rounding downwards. Returns a double in type, although the value has zero fractional part.
  • ceil for rounding upwards. Returns a double in type, although the value has zero fractional part.

For going the other way there is:

  • double converts a number to double-precision floating-point form.