Here's a short rounding routine that uses sprintf and does produce correct results.

#!/usr/bin/perl -w

while (<DATA>) { print round($_,2), "\n" }

sub round {
        my ($number, $places) = @_;
        my $tenpower = 10**$places;
        return (sprintf "%.0f", $number * $tenpower)/$tenpower;
}

__END__
1.655
1.755

Regards,

Vic

At 1:49 PM -0500 10/13/03, Bill Stephenson wrote:
I've got a script that takes numbers similar to those below and then rounds
them and adds them together using code similar to what is below.


#!/usr/bin/perl -w


use strict;

my $item_1 = "1.655";

my $item_2 = "1.755";

my $rnd_1 = (sprintf qq~%.2f~, $item_1);

my $rnd_2 = (sprintf qq~%.2f~, $item_2);

print "$rnd_1, $rnd_2";


The code above prints this result (system 10.1.5, perl 5.6.0):


1.66, 1.75

But shouldn't it be:

1.66, 1.76

or:

1.65, 1.75

I'm no math wizard, so if someone could please take the time and tell what
I'm missing here I would very much appreciate it!


--


Bill Stephenson
www.PerlHelp.com
1-417-546-5593

-- Vic Norton vic at norton dot name

Reply via email to