You could also check How do I round a floating point number?
One other important thing to remember when rounding is that int just truncates anything past the decimal place off, so it doesn't really round. If you want it to work like a round do int($num+0.5);
vroom | Tim Vroom | vroom@cs.hope.edu
| [reply] [d/l] |
sub round ($$) {
sprintf "%.$_[1]f", $_[0];
}
my $rounded = round 3.165232, 2;
| [reply] [d/l] |
I pulled this one out of my bag of holding today...
sub round {
my ($number,$decimals) = @_;
return substr($number+("0." . "0" x $decimals . "5"),
0, $decimals+length(int($number))+1);
}
brother Willem
--
wrvhage@science.uva.nl.nl | http://www.xs4all.nl/~wrvh
| [reply] |
I'm a complete amateur trying to teach myself to program. After two days of scouring the Camel and Llama books (nobody tell merlyn), your subroutine was exactly what I wanted. I should have checked the monks first. Thank you for this.
| [reply] |
It is amazing to me that this type of function is not built in. I just wanted to thank you for sharing. This simple yet obvious solution is great.
Thanks again and God bless,
-David
| [reply] |
Thanks for the answers! I obviously did not really understand
what sprintf did.
| [reply] |
One quick place to look for information on *printf is man 3 printf. It's the C manpage on printf, but perl implements it more or less just like in C. You'll probably find it very helpful in the future for printing anything in the format you like.
I think I'll write a comprehensive tutorial on *printf at some point, unless someone knows about a good one already out there. At least in my version of perldocs, the printf page just says 'just like in C'.
| [reply] [d/l] |