round number to 2 decimal places

Micheal picture Micheal · Apr 18, 2012 · Viewed 47.4k times · Source

I need to round a number to two decimal places. Right now the following rounds to the nearest integer I guess

puts [expr {round($total_rate)}]

If I do something like below it does not work. Is there another way around?

puts [expr {round($total_rate,2)}]

Answer

Donal Fellows picture Donal Fellows · Apr 19, 2012

The simplest way to round to a specific number of decimal places is with format:

puts [format "%.2f" $total_rate]

Be aware that if you're using the rounded value for further calculations instead of display to users, most values that you print using rounding to X decimal places will not have an exact representation in binary arithmetic (which Tcl uses internally, like vast numbers of other programming languages). It's best to reserve rounding to a specific number of DPs to the point where you're showing values to people.