Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Formating Currency Fields In Perl

Status
Not open for further replies.

abraxas

Programmer
Jan 15, 2001
75
AU
G'Day,
For the first time in 5 years I find it necessary to format $#####.## fields in Perl. How does one do it? My hard copy references are rather oblique in conveying usage of
"format =" and online refs refer to entirely other matters.

Simply, I wish to $TotalVal= $Quantity * $Price;
eg. $TotalVal = 5 * 5.50 should return 27.50 but alas returns 27.5. Is there a way of setting currency or at least deciding decimal significance in Perl? The result is to be shoved into html.

Much Obliged if any one can help.
abraxas
 
Assuming you are not passing in values with fractional cents...... This completely neglects rounding partial cents up or down.

Code:
#!/usr/local/bin/perl
$str = money(5*5.5);
print "$str\n";

sub money
{
my $money = shift;
if ($money !~ /.*\.\d+/) { $money .= '.00'; }
$money =~ s/\d+\.\d$/$&0/;
$money = '$'.$money;
return ($money);
}

HTH


keep the rudder amid ship and beware the odd typo
 
Try using sprintf to format the numbers for output:
Code:
$printable = sprintf("%1.2f", $number);
The format string above, similar to a C format string, will format the number to at least one character to the left of the decimal point (i.e. 0.50), and two places to the right of the decimal. The sprintf will also ROUND $number if it contains more than two decimal places. Note that sprintf rounds DOWN on an even 1/2 cent (i.e. .005) rather than up, so you might want to add 1/100 of a cent (.0001) to the amount before rounding to foce sprintf to round 1/2 cent upward. This will do that:
Code:
$printable = sprintf("%1.2f", $number + .0001);
You don't need to put the formatted number into a different variable either, you can have the same var name on the left side of the equal and in the sprintf. perl will still be able to use it as a number in a calculation if required, although you'll have to format it again if you do use it in another calculation. Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
much better.


keep the rudder amid ship and beware the odd typo
 
Wow,
Thank you for the lightning responses and their deadly accuracy. They both worked a treat. Sprintf() is very powerful, isn't it?

Many Thanks!
abraxas
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top