PDA

View Full Version : Round Decimals


magicskeptic
07-02-2005, 06:06 AM
Hey, I've made a web poll cgi, and one of the things it shows is the percentage of the certain option that's been selected. But the percentages all have long decimals and it looks ugly. How can I round the decimals of the percentages down to just 1 decimal?

I tried googling this and I just kept finding how to do it with javascript, but nothing on how to do it in perl.

Jacob

FishMonger
07-02-2005, 08:00 AM
Use either printf or sprintf.

Execute this command for the documentation:
perldoc -f sprintf

example, Round number to 3 digits after decimal point
$rounded = sprintf("%.3f", $number);

rwedge
07-02-2005, 08:02 AM
You can read about printf and sprintf here (http://www.perldoc.com/perl5.8.4/pod/func/sprintf.html) for $number (42.213, 42.21, 42.2, 42, -17.231, -17.23, -17.2, -17) {
my $rounded = sprintf("%.2f", $number);
print "$number rounded to two decimals is $rounded\n";
}