Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re^2: Problems with number resolution

by Anonymous Monk
on Jan 01, 2018 at 19:14 UTC ( #1206519=note: print w/replies, xml ) Need Help??

in reply to Re: Problems with number resolution
in thread Problems with number resolution

Thanks Poj,

To have the sum as integer, the (number*100) has to be converted to an integer using round.
use Math::Round qw/round/; my @nr=('32431.19', '20', '-10', '-31800'); my $x=0; foreach (@nr) { $x+=round($_*100); print "$_ => ".$x/100 ."\n"; }

Replies are listed 'Best First'.
Re^3: Problems with number resolution
by Laurent_R (Canon) on Jan 02, 2018 at 00:19 UTC
    Why do you use round here? I don't think you need it. Or can your input numbers have more than two decimals? I think you said that there could be only two decimal places.

    Another point is that I don't see any reason to print incremental results each time through the look (except possibly for debugging purposes). Put the print statement after the end of the foreach loop.

    And you might want to use printf instead of print in this specific case. In fact, using printf might be the only change that you need in your original code, as shown with this example under the Perl debugger:

    DB<1> @nr=('32431.19', '20', '-10', '-31800'); DB<2> $x=0; DB<3> $x += $_ for @nr; DB<4> print $x 641.189999999999 DB<5> printf '%.2f', $x; 641.19

      The numbers have maximum 2 digits. The code is just for debugging, extracting the problem from a larger code, to have some small code to play. In the original code all sums are stored in an array and used later. Therefore printf is only a solution for the small debug code.

      You need the round. The effect is much more seldom when using *100, but still exists. Please see:
      my @nr=('34455.28','-33907.55'); my $x=0; foreach (@nr) { $x+=($_*100); print "$_ => ".$x/100 ."\n"; } 34455.28 => 34455.28 -33907.55 => 547.729999999995
        Yes, I wrote my message too quickly, you're right that some form of rounding is needed if you want to make sure to use integer addition; multiplying the numbers by 100 is not always sufficient to get proper integers.

        Having said that, I still think that using just printf (or sprintf to convert the results and store them in an array) on the final result is probably sufficient to get the right precision (unless you're really adding huge volumes of numbers).

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1206519]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (7)
As of 2018-06-19 14:57 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (114 votes). Check out past polls.