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 derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Displaying perl variables in an HTML table as decimal values

Status
Not open for further replies.

CherylD

Programmer
Joined
May 1, 2001
Messages
107
Location
CA
I'm writing a CGI scripts that does some minor math calcuations. There is a constant declared in the script as
my $price = 7.00;
and then multiplied with a quantity that is pulled out of a database and assigned to the variable $weeks.

The problem is when I display the product of these two numbers it isn't a decimal value. I am trying to display them in table. The correct values always appear but no '.00'. Can someone please help?

Thanks.
Cheryl
 
Well, if you are multiplying two int's together, there won't be any .00 seing as they are not floating point values.

But, this will format the value so that there are only values to the hundreth decimal place.

#!/usr/bin/perl
$value = sin 1.0;
printf("%.2f",$value);

That should do it.

Hope this helps.

-Vic vic cherubini
vikter@epicsoftware.com
====
Knows: Perl, HTML, JavScript, C/C++, PHP, Flash, Director
====
 
Keep in mind, too, that sprintf is available for formatting the number to store in a variable. printf will output the string directly to a filehandle (or STDOUT) and return a 1 if successful which would be the value stored in your variable. So..

$f = printf "%.2f",15;
$f would equal 1

$f = sprintf "%.2f",15;
$f would equal 15.00

brendanc@icehouse.net
 
Also keep in mind that printf and sprintf always round DOWN when the last digit is 5 (i.e. 1.115 would be rounded to 1.11 rather than 1.12). If this isn't what you want, modify the code like this:
Code:
$f = sprintf("%1.2f", $amt + .0001);
It adds 1/100 of a cent to the amount before rounding and formatting. It won't have any other noticable effect except to force rounding UP on an even 1/2 cent.
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top