11-19-2017, 06:06 +0100
thommey  03-04-2006, 22:08   | [TCL] Round a number (5.55 => 5.6 instead of 5.5 as round() would do it) Jabber
Member since 03/2004
62 Posts
proc round {number {digits 0}} {
    return [expr {round(pow(10,$digits)*$number)/pow(10,$digits)}]

robeadam  10-28-2011, 01:29  
Member since 10/2011
1 Post
Location: Johns Creek, GA
This was exactly what I was looking for but after playing with it a bit, I'd recommend 1 change.  If the user passes the proc 1 digit, the returned value would be \d.\d which is great.  But if the user doesn't pass digits or passes it as 0, the return will be \d.0 which is inaccurate.  So the enhancement would be:

proc round {number {digits 0}} {

   if { $digits} {
      return [expr {round(pow(10,$digits)*$number)/pow(10,$digits)}]
   } else {
      return [ int [expr {round(pow(10,$digits)*$number)/pow(10,$digits)}]]

Thanks for the snippet, helped a lot.
Advanced options for this topic:

Ignore this topic (Do not list this topic in the "unread topics" search. You are currently not ignoring this topic.)
Hide this topic (Hidden topics are not displayed in the topics list. This topic is currently not hidden.)
Go to forum

Unclassified NewsBoard 1.5.3-d | © 2003-4 by Yves Goergen