htmanning has asked for the wisdom of the Perl Monks concerning the following question:

Monks, I'm adding up currency like $49.95 + $39.95. The result I'm getting is $89.9. How can I force Perl to add the extra zero when appropriate? Thanks.

Replies are listed 'Best First'.
Re: Force currency view
by SuicideJunkie (Vicar) on Feb 07, 2011 at 22:23 UTC
    There is no such thing as currency. You can format things nicely however:
    printf('$%.2f', $number)
    c:\>perl -e "printf('$%.2f', 12.9)" $12.90 > _
      See also sprintf if you want to do something more with the result than just print it.
Re: Force currency view
by MidLifeXis (Monsignor) on Feb 08, 2011 at 14:28 UTC
      Your first link ("What Every Scientist...") has gone 404. I found another copy of it elsewhere. While you can still read the one at sun.com in the Google cache, I figure that's not reliable since Oracle is re-arranging a lot, so I have a full like to it here. (I'm printing the full link as is for reference.)

      www.math.umd.edu/~jkolesar/mait613/floating_point_math.pdf
      Wish I could double-upvote this!
      -Bib

      For the same reasons, it is wise to use “currency” field-types in your SQL database if it has them ... and if its implementation of that field-type is not merely “in name only.”   For example, in the well-known case of Microsoft Access (JET), currency is implemented as a scaled integer:   the value is multiplied by 10,000, so that there is a fixed 4-digit accuracy.   Since Perl does not (AFAIK...) have direct support for such a data-type, you might not wish to do a long series of calculations involving currency in Perl, whereas a CALC SUM() query (since it is being carried out by the SQL engine) would retain accuracy.

      Ironically enough, there are countless examples out there of spreadsheets which have numeric-precision issues of this type.

Re: Force currency view
by pavunkumar (Scribe) on Feb 08, 2011 at 05:44 UTC
     Try this one.....
    
    # When $val has normal integer . $val=89.9 ; printf ( "%.2f", $val ) ;
    Or.... # When $val has dollar sign .
    $val='$89.9'; printf ('$'."%.2f",substr($val, 1,length($val))) ;
Re: Force currency view
by HalNineThousand (Beadle) on Feb 08, 2011 at 08:21 UTC

    I just use a regex to see if it's one or two digits at the end (after the period), and if it's one, I add a 0, like this:

    $zero = "0"; $total =~ s/\.(\d)$/.$1$zero/g;

    I'm sure there's a way to specify the digit "0" after the $1, but I can't think of it right off, so I just use another string set to 0 for it.

    Update: I might add that you can use print formatting, but that only formats the output at that one point, for one reason. What if you need the data formatted for something else? One example (which I have to use a LOT) is if you're inserting the data into a MySQL table.