Search code examples
tclroundingexpr

tcl expr not rounding like i expect


Im new to tcl and i have these numbers:

set a 565056236086 set b 488193341805

the output of $a / $b is 1,157443552992375

When i use the following code

set num [expr {double(round(100*$a / $b))/100}]

the output is: 1,15

but i want 1.16 how can i round it like that?


Solution

  • You need to make either a or b a double before doing the operations. Also, round returns an integer, so you either need to convert it to double too, or divide by a double:

    set num [expr {round(100*double($a) / $b)/100.0}]
    # 1.16
    

    Or if you specifically need to round up, then, you can use ceil (since this one returns a double, you don't need to divide by a double):

    set num [expr {ceil(100*double($a) / $b)/100}]
    # 1.16