in reply to Preferred Methods
sub roundThatBadDog { my $seconds = shift; return sprintf("%d", $seconds); }
Or alternatively, if you are wanting precision, replace the %d with %.xf where x is a integer value representing the order of decimal precision desired.
Update
In response to japhy's comments, I checked out the FAQ and ran a few timing tests to compare.
From my reading, the comments in the FAQ hardly suggest the avoidance of sprintf function for rounding purposes but rather the use of a more intrinsic, known method of rounding (such as those submitted by japhy here) for sensitive or high-value operations. The example given is a financial environment where the FAQ rightly suggests that a programmer should implement their own rounding code rather than relying on system functions.
With regard to a timing comparison, the following is the output - Make of it what you will :-)
Benchmark: timing 100000 iterations of japhy, rob_au... japhy: 3 wallclock secs ( 4.13 usr + 0.00 sys = 4.13 CPU) @ 24 +213.08/s (n=100000) rob_au: 4 wallclock secs ( 4.23 usr + 0.00 sys = 4.23 CPU) @ 23 +640.66/s (n=100000)
Update
These results may not be truly indicative of function performance, and may I add, not intendedly so. japhy discusses performance differences in his more comprehensive comparison here. ++japhy!
#!/usr/bin/perl use Benchmark; use strict; timethese(100000, { 'rob_au' => q! my @values = ( 1.24, 5.43, -98.54, -73.667, 0.67, 2.34, 76.89, + -999.99, 34.52, 67.89 ); foreach my $value (@values) { my $result = sprintf("%d", $value); } !, 'japhy' => q! my @values = ( 1.24, 5.43, -98.54, -73.667, 0.67, 2.34, 76.89, + -999.99, 34.52, 67.89 ); foreach my $value (@values) { my $result = int($value * 10**0 + .5 * ($value < 0 ? -1 : +1)) / 10**0; } ! });
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Preferred Methods
by japhy (Canon) on Jan 14, 2002 at 11:33 UTC | |
|
Re: Re: Preferred Methods
by japhy (Canon) on Jan 14, 2002 at 09:27 UTC |