round number to 2 decimal places

Tag: tcl , round Author: ygtzz567 Date: 2012-04-02

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)}]

Best Answer

expr {double(round(100*$total_rate))/100}

example

% set total_rate 1.5678
1.5678
% expr {double(round(100*$total_rate))/100}
1.57
% set total_rate 1.4321
1.4321
% expr {double(round(100*$total_rate))/100}
1.43

comments:

proc tcl::mathfunc::roundto {value decimalplaces} {expr {round(10**$decimalplaces*$value)/10.0**$decimalplaces}}; expr {roundto($total_rate, 2)}

Other Answer1

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.

Other Answer2

A co-worker of mine wrote this round to any number of decimal places (well, up to 10!)

set zerostr 000000000000000
set rounded_num [expr round($number * pow(10,$decimal_places))/pow(10,$decimal_places)]
append rounded_num [string range $zerostr 0 [expr [string length [expr int($number)]] + $decimal_places - [string length $rounded_num]]]