Gossamer Forum
Home : General : Perl Programming :

rounding numbers off

Quote Reply
rounding numbers off
Below is the entire code, what do I need to add to round the resulting number off.

#!/usr/local/bin/perl

# simple math calculations

$test = 7 / 3;

print "Content-type: text/html\n\n";

print "$test";

Thanks
Quote Reply
Re: rounding numbers off In reply to
Me again!

I'm not doubting you Alex, but is the Perl FAQ inaccurate so? Or do prinf and sprintf return a different result when you're removing the decimal point? This is from perlfaq4 (as if you didn't know!):

language.perl.com/newdocs/pod/perlfaq4.html#Does_Perl_have_a_round_functio

Quote:
Does Perl have a round() function? What about ceil() and floor()? Trig functions?

Remember that int() merely truncates toward 0. For rounding to a certain number of digits, sprintf() or printf() is usually the easiest route.

printf("%.3f", 3.1415926535); # prints 3.142

As I said, I'm not doubting you, I just want to make sure I get it right in future.

*fingers crossed he doesn't take offense* Smile

adam

[This message has been edited by dahamsta (edited May 27, 1999).]
Quote Reply
Re: rounding numbers off In reply to
Use printf() or sprintf(). I wouldn't be able to explain the difference, maybe someone else will oblige. I'm always chuffed to learn the intracacies meself!

Code:
#!/usr/local/bin/perl
$test = 7 / 3;
$rounded = sprintf("%.0f\n", $test);
print "Content-type: text/html\n\n";
print "Test = $test<br>";
print "Rounded = $rounded";
exit;

The number of digits the integer is rounded to is determined by the first attribute in brackets:

No decimal point:
$rounded = sprintf("%.0f\n", $test);

Decimal point, rounded to two digits:
$rounded = sprintf("%.2f\n", $test);

Cheers,
adam

ps. Not too sure about that line break (\n) in the sprintf() function, I just pulled it from one of my scripts. Try it without...

[This message has been edited by dahamsta (edited May 27, 1999).]
Quote Reply
Re: rounding numbers off In reply to
printf() will print the output, where sprintf() will return the output as a string. Also the newline is not neccessary.

As for rounding, neither will actually round, but only remove the decimals. If you want to round with no decimals use:

$test = int ($test + 0.5);

If you want to round to two decimals:

$test = sprintf ("%.2f", ($test + 0.5));

Cheers,

Alex
Quote Reply
Re: rounding numbers off In reply to
Ooops, I stand corrected. (s)printf does indeed do the rounding for you, no need to add 0.5.

Cheers,

Alex
Quote Reply
Re: rounding numbers off In reply to
Ok, so now that we know sprintf and printf round. How would I get something to truncate to, say for instance the thenths, without rounding?