***** infoCopter.com/perl *****
Round with precision to 5 Swiss Rp.Solution for the Swiss currencyMeta Code#!/usr/bin/perl -w my $amount = $ARGV[0]; require "rounder_include.pl"; print &round_amount($amount), "\n"; Samples# perl test.pl 33.32 is rounded 33.30 33.99 is rounded 34.00 33.38 is rounded 33.40 33.33 is rounded 33.35 99.99 is rounded 100.00 110.58 is rounded 110.60 19.03 is rounded 19.05 ImplementationI know there is a better solution but it's late in the nite and this work well ;-)
my @tests = qw(33.32 33.99 33.38 33.33 99.99 110.58 19.03);
print "$_\t is rounded\t", &round_amount($_), "\n" foreach @tests;
sub round_amount ($) {
my $amount = $_[0];
my $frac = sprintf("%.2f", $amount - int($amount));
my $ten = substr(sprintf("%02d", ($frac * 100)), 0, 1);
my $decmak = substr(sprintf("%02d", ($frac * 100)), 1, 1);
my $result = my $rounded = 0;
if (!($decmak % 5) or !$decmak) {
# nothing to round
$rounded = sprintf("%.2f", $amount);
}
else {
$result = ($decmak == 1 or $decmak == 2 or $decmak == 8 or $decmak == 9) ? 0 : 5;
$rounded = int($amount) . '.' . $ten . $result;
$rounded += .1 if $decmak > 7;
$rounded = sprintf("%.2f", $rounded);
}
$rounded;
}
|