in reply to Currency Format Issue
#!/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
|
|---|