in reply to Simple Rounding

$a = 1100.64686081907; $b = int($a*100+.5)/100;
but if you just want to print it, (s)printf() would be the better choice.

Search, Ask, Know

Replies are listed 'Best First'.
Blushing at the facts
by TomDLux (Vicar) on Mar 25, 2004 at 16:30 UTC

    My first thought was, 'Silly guy, why is he writing C code? Doesn't he know the Perl(tm) way?'.

    Then I thought, sprintf() is expensive .... how fast is it to run the integer math?

    --
    TTTATCGGTCGTTATATAGATGTTTGCA

      There is a subtle, but important difference between
      $var1 = sprintf "%.2f" => $number;
      and
      $var2 = int ($number * 100 + .5) / 100;
      $var1 is a PV, that is, the interval variable has a string value, but not a numeric value, while $var2 is an NV, that is, it has a numeric value, but not a string value. This means that $var1 will have two digits after the decimal point when printed - sprintf has garanteed that. But that's not necessarely true for $var2. Since you cannot represent 1/100 exactly in binary, you left the possibility open that if you stringify the number, you end up with more than 2 characters after the decimal point. Now, it may not happen in a thousand testcases, but can you guarantee it will never happen?

      See perldoc -q decimal.