perldiverx has asked for the wisdom of the Perl Monks concerning the following question:

I have a subroutine that's outputting a float correctly, however when added to a value the last return gives a Euler's number for some reason. Does anyone know why this is and how can I just get the 0 that I'm expecting? Below is my code:
use strict; use warnings; my @vals = ( '00000000{', '00000000{', '00000000{', '00000369I', '00000020{', '00000000{', '00000100}', '00000289R',); my $total; foreach (@vals) { $total += calc_total($_); print "\$total: $total\n"; } sub calc_total { my $val = shift; my %pos_map = ('A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, ' +F' => 6, 'G' => 7, 'H' => 8, 'I' => 9, '{' => 0); my %neg_map = ('J' => 1, 'K' => 2, 'L' => 3, 'M' => 4, 'N' => 5, ' +O' => 6, 'P' => 7, 'Q' => 8, 'R' => 9, '}' => 0); my $outval = substr($val, 0, 8); if (exists($pos_map{substr($val, -1, 1)})) { $outval .= $pos_map{substr($val, -1, 1)}; } elsif (exists($neg_map{substr($val, -1, 1)})) { $outval .= $neg_map{substr($val, -1, 1)}; $outval *= -1; } else { print "Could not map total for: $val\n"; } print "in the sub: " . sprintf("%.2f", $outval/100) . "\n"; return sprintf("%.2f", $outval/100); }
I'm using Perl 5.16, too.

Replies are listed 'Best First'.
Re: Adding floats (integers)
by tye (Sage) on Sep 17, 2014 at 20:16 UTC
      This worked great, thanks
Re: Adding floats
by AnomalousMonk (Archbishop) on Sep 17, 2014 at 20:10 UTC
Re: Adding floats
by AnomalousMonk (Archbishop) on Sep 19, 2014 at 01:59 UTC

    Just for the heck of it, here's an approach that provides total encapsulation in an absolutely minimal 'module', with a testing scheme. Take note of the exceptions: are they all really what you want?