Rounding in Tcl

MB : The subject of this page is to analyse the methods to round a double real value into an integer. The Tcl language provide 4 commands :

  • int arg : The integer part of arg is determined, and then the low order bits of that integer value up to the machine word size are returned as an integer value.
  • ceil arg: Returns the smallest integral floating-point value (i.e. with a zero fractional part) not less than arg.
  • floor arg : Returns the largest integral floating-point value (i.e. with a zero fractional part) not greater than arg.
  • round arg : If arg is an integer value, returns arg, otherwise converts arg to integer by rounding and returns the converted value.

It is not obvious to see the effect of these operators on a given data, and that may generate bugs if the wrong operator is chosen. The following is a small Tcl script which shows the effect of the 4 operators on 8 real values from 0 to 2.

  for {set i 0} {$i<9} {incr i} {
  set x [expr {double($i)/4.0}]
  set ceil [expr {ceil($x)}]
  set floor [expr {floor($x)}]
  set round [expr {round($x)}]
  set int [expr {int($x)}]
  puts "ceil($x)=\t $ceil, \t floor($x)=\t $floor, \t round($x)=\t $round, \t int($x)=\t $int"

And this is the result.


See also