in reply to comparing two amounts of money.

Without posting your code, it's tough to be sure what's going on here, but it appears that you are confusing a display format with an internal one. In other words, you would only want the dollar sign on the number for display purposes.

perl -e 'if ( q|$201.00| > q|$200| ) {print 1}else{print 0}'

That prints zero, which is correct, but may not be what you expect. Either strip the dollar sign or use a regex to extract the number into another variable.

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Replies are listed 'Best First'.
Re: (Ovid) Re: comparing two amounts of money.
by epaphus2 (Novice) on Dec 21, 2001 at 23:20 UTC
    So you mean if ($var1 > $var2) { ... } will compare the formats without any problem? That is if there is no dollar sign, is that what youre saying? Doesnt it "crash" with the "." or "," when comparing? I thought numbers had to be plan integers to compare. Such as 52 > 56 Tnx

      Your insticts were correct to use if ( $var1 > $var2 ) {...}. Let me explain this in a bit more detail.

      Perl's typing is based around data structures (scalars, arrays, hashes, etc) and not data types. Other languages that use typing typically use things like int, float, char, etc. Perl also deals with things like that, but does it behind the scenes. When dealing with a string, if you try to perform mathematical operations on it, Perl will (usually¹) try to convert the string to a number and perform the mathematical operations. If a string can't be converted to a number, it's considered to be "zero". For example, here's a little blow to my ego:

      $ perl -e 'print "Ovid" + 0' 0

      When you try to compare a string with a dollar sign, Perl sees the dollar sign and just converts the string to a zero. For my example above, you may have been mislead (my $apologies). When comparing strings, you would use the string comparison operators such as gt, ge, lt, and le. However, since those are comparing strings and not numbers, your results will not be suitable for mathematical operations.

      So, Perl will not "crash" when you have a "." or "," in your string. The period will be recognized as a decimal point. There is one thing to be wary of, though: when trying to convert a string to a number, Perl still take the numbers at the beginning of string and use those:

      $ perl -e 'print "123Ovid" + 4' 127

      So, you either need to strip those dollar signs from your strings or not add those dollar signs until you're ready to output them to a file, report, screen, etc.

      Cheers,
      Ovid

      1. The unary increment (++) and (--) decrement operators are counter-examples.

      Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.