
mhx
Enthusiast
/ Moderator
Jun 30, 2001, 8:53 AM
Post #6 of 8
(620 views)
|
Hi japhy, just wanted to tell you there's a typo in your round function. Perhaps the character got lost somewhere, this also happened to me when I posted a regex. should rather be Anyone can safely ignore the rest of this post. It's based on mislead thoughts and mostly wrong. I've tried to like the function, but the int made we worry. I thought there were problems with large numbers. But I've tried it, it works very fine. Anyway, I've looked up int in perlfunc and found:
int EXPR int Returns the integer portion of EXPR. If EXPR is omitted, uses `$_'. You should not use this function for rounding: one because it truncates towards `0', and two because machine representations of floating point numbers can sometimes produce counterintuitive results. For example, `int(-6.725/0.025)' produces -268 rather than the correct -269; that's because it's really more like -268.99999999999994315658 instead. Usually, the `sprintf', `printf', or the `POSIX::floor' and `POSIX::ceil' functions will serve you better than will int(). I don't want to justify myself, I don't like the sprintf solution either. Best thing would be if Perl would have such a function built-in. Or we could modify your approach:
use POSIX; sub round { my ($num, $places) = @_; $places ||= 0; # default to rounding to an integer my $sign = ($num > 0) ? 1 : -1; # pos or neg? $num *= 10**$places; # shift decimal point $num = POSIX::floor($num + .5 * $sign); # add (or subtract) .5, truncate return $num / 10**$places; # put decimal point back } I think that's way better than sprintf, and safer than the int approach. -- Marcus
(This post was edited by mhx on Jun 30, 2001, 12:18 PM)
|