in reply to Re^2: problem with variables
in thread problem with variables

Works fine for me:
#!/usr/bin/perl use strict; use warnings; my $num1 = 1234.56789; my $num2 = 1234.56789111; if ( $num1 == $num2 ) { print "equal.\n"; } else { print "Please don't try to check for equality of floats that way.\ +n"; } if ( sprintf( "%.3f", $num1 ) == sprintf( "%.3f", $num2 ) ) { print "Yup, they show up as equal.\n"; } if ( sprintf( "%.3f", $num1 ) eq sprintf( "%.3f", $num2 ) ) { print "Yup. This works too.\n"; }
output:
Please don't try to check for equality of floats that way. Yup, they show up as equal. Yup. This works too.

Replies are listed 'Best First'.
Re^4: problem with variables
by JohnMG (Beadle) on Oct 19, 2005 at 18:57 UTC
    Actually, now that brain is in gear, I think you *always* want to use eq rather than == for comparing floats. If you use
    sprintf( "%.3f", $num1 ) == sprintf( "%.3f", $num2 )
    that just puts you right back to where you started: comparing floats with ==.
      Yes, but if the strings are eq, the floats that come from those strings will be ==. It's a deterministic thing. That said, it makes more sense to compare them with eq, since the output of sprintf is a string. Why force the conversion back?

      Caution: Contents may have been coded under pressure.