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

Hi Monks!
I need to check currency values and format them, my question is what is the best way. I am working on this code, but if the values checked doesn't have decimal on them the code will not work, any suggestions? Thanks!
#!/usr/bin/perl -w use strict; my $dollar="100"; #test 1 #my $dollar="100.000"; #test 2 #my $dollar="10.000"; #test 3 my $amount= f_currency($dollar); print "Testing=$amount\n"; sub f_currency { my $num = shift @_; my $number; #make sure that the amount entering this sub has the decimal point fol +lowed by two numbers, if not dont go there. if($num=~/\d+\.\d{2}$/g) # This regular is not checking properly { $number = sprintf "%.2f", $num; # Add one comma each time through the do-nothing loop 1 while $number =~ s/^(-?\d+)(\d\d\d)/$1,$2/; # Put the dollar sign in the right place $number =~ s/^(-?)/$1\$/; return $number; }else{ #if the number dotn have the expected format just add the $ sig +n in front of it. $num="\$".$num; return $num; } }

Replies are listed 'Best First'.
Re: Currency Format Issue
by JavaFan (Canon) on Aug 26, 2010 at 14:10 UTC
    I'm not sure what you want. You test if the input is a number ending in two decimals, and then complain it "doesn't work" if you give it a number without two decimals.

    The solution is obvious, isn't? Either give it a number ending in two decimals, or don't check for it.

      I guess what one is looking for would be if the number is not on the right format, still check it and format it properly. That would be where your answer should come up!
Re: Currency Format Issue
by toolic (Bishop) on Aug 26, 2010 at 14:21 UTC
Re: Currency Format Issue
by Marshall (Canon) on Aug 26, 2010 at 20:59 UTC
    I just took your code as a starting point and modified it a bit. It would appear that just checking whether a decimal exists or not is sufficient. Take out that if logic if you want all data to be formatted like $x.yy.
    #!/usr/bin/perl -w use strict; foreach my $in qw(-10000000 1000.000 10.000 9.999 10 10.1 0 12345 5.) { print "in = $in \tformatted = ",f_currency($in),"\n"; } sub f_currency { my $num = shift; my $rounded = $num; if ($num =~ m|\.|) { $rounded = sprintf("%.2f", $num); #rounds to 2 dec places } #add commas, all the "work" happens in the while condition while ($rounded =~ s/^(-?\d+)(\d\d\d)/$1,$2/){}; return ('$'.$rounded); } __END__ prints: in = -10000000 formatted = $-10,000,000 in = 1000.000 formatted = $1,000.00 in = 10.000 formatted = $10.00 in = 9.999 formatted = $10.00 in = 10 formatted = $10 in = 10.1 formatted = $10.10 in = 0 formatted = $0 in = 12345 formatted = $12,345 in = 5. formatted = $5.00