Thursday, March 10, 2011

Converting numeric values to currency formatted numbers in PERL

While developing a particular report in Perl, I just noticed that my output for currency values are just numbers without commas and decimal points. So, I do some research to check for an existing function in Perl that simply do this conversion but didn't find anything.. No choice.. I have to create a sub function that converts numeric values to currency values, and I did and now sharing this to you..

Please see sample code and sub function that I just created. Hope you like it!!

#!/usr/bin/perl

$number = 4356789; # sample data
$currency = &convert_to_currency($number);

print "Here we go in Peso value: P$currency\n";

sub convert_to_currency
{
        my ($number) = @_;

        $number = sprintf("%.2f", $number);
        $number = "$1,$2$3" while ($number =~ /(.*\d)(\d\d\d)(.*)/i);
        return $number;
}



1;

No comments:

Post a Comment