in reply to Re^3: Coping with decimals
in thread Coping with decimals

Having a mental map that considers strings numbers and numbers strings allows one to make subtle errors in their programs.

In fact, sprintf returns a string after doing an arithmatic operation. Compare a 2 deciaml point operation via sprintf:

my $num = 4.62899; $round = sprintf "%.2f", $num; print "$round\n";

prints 4.63, which is not a trimming of the string to two decimal places.

For another example consider this snip and output.

my $string = "0.0"; print "string $string is ", ($string ? "True" : "False"), "\n"; print "string $string is ", ($string+0 ? "True" : "False"), "\n";

Which prints:
string 0.0 is True
string 0.0 is False

Be Appropriate && Follow Your Curiosity

Replies are listed 'Best First'.
Re^5: Coping with decimals
by tlm (Prior) on Jun 02, 2005 at 16:47 UTC

    prints 4.63, which is not a trimming of the string to two decimal places.

    That's not a bug; it's a feature :-) . Seriously, that's the documented behavior for sprintf, and precisely why it is the standard way to do rounding in Perl.

    the lowliest monk