in reply to Integer vs Float during addition

Actually, that was a cleaned-up example, the actual one was using
if( $cost) { .... }
but I was getting different results (ie if() was true/false) depending on whether the $cost of 0.00 was extracted via DBI::MYSQL and then left untouched, or extracted via DBI::MYSQL and then added to an integer zero.
Took me a while to figure out why the optional code path was /was not being followed.
ie not just an academic qn and nothing to do with printing as such.
Cheers
Chris

Replies are listed 'Best First'.
Re^2: Integer vs Float during addition
by Zaxo (Archbishop) on Jun 29, 2006 at 04:39 UTC

    Ok, you took it the opposite direction. Boolean context doesn't force anything. Print forces to string. 0+ forces to number.

    The string '0.00' is true, but numeric zero is false.

    After Compline,
    Zaxo

      More specifically, string '0.00' is true but string '0' is false. This tends to surprise C-to-Perl newcomers. So if someone got a string and they weren't sure if it was natural or sprintf-formatted, it could lead to bugs in logic.
      use Data::Dumper; for (0, '', '0', '00', '0.0', '0.00', undef) { print (($_? 'TRUE' : 'FALSE'), ': ', Dumper($_)); }

      --
      [ e d @ h a l l e y . c c ]

Re^2: Integer vs Float during addition
by Moron (Curate) on Jun 29, 2006 at 12:41 UTC
    One way to do that is:
    if ( NumericTrue( $cost ) ) { ... } sub NumericTrue{ return shift()*1.0; }
    (Updated to allow e.g. 99 cents to be a cost.)

    -M

    Free your mind

      Or return 0+shift();