good chemistry is complicated,and a little bit messy -LW PerlMonks

### Re^5: accurately rounding numbers for percentages

by ww (Bishop)
 on Aug 03, 2009 at 04:13 UTC ( #785336=note: print w/replies, xml ) Need Help??

Your made yourself clear enough in the OP but you don't seem to like the answers (or won't understand them?).

The numbers in your latest post, 30, 23, and 13, happen to be what I gather your mean by a "nice" case; that is, when calculated as percentages of their total and rounded, the percentages add up (nicely) to 100.

Here's a case where the numbers are not "nice" and where a disclaimer is the only reasonable solution (fudging is NOT, IMO, reasonable):

```#!/usr/bin/perl
use strict;
use warnings;
#785290

my \$Google=30; my \$Yahoo=23; my \$Bing=12;
my \$sum=\$Google + \$Yahoo + \$Bing;

my \$yahoo_percent = \$Yahoo/\$sum;
print "\tY: \$yahoo_percent";
my \$bing_percent = \$Bing/\$sum;
print "\tB: \$bing_percent \n";

my \$total = (\$google_percent + \$yahoo_percent + \$bing_percent);

my \$roundedY = sprintf("%.2f", \$yahoo_percent);
my \$roundedB = sprintf("%.2f", \$bing_percent);
my \$rounded = sprintf("%.2f", \$total);
print "Google: \$roundedG; Yahoo: \$roundedY; Bing: \$roundedB; Total: \$r
+ounded \n";

print "%\n";
printf ('%.0f', ((\$Yahoo/\$sum)*100));
print "%\n";
printf ('%.0f', ((\$Bing/\$sum)*100));
print "%\n";
print \$rounded*100 . "% (Percentages may not add up to 100 because of
+rounding errors!)\n";

Create A New User
Node Status?
node history
Node Type: note [id://785336]
help
Chatterbox?
 [davido]: And remember; time is hard. :) As soon as you think, I've got this, you'll discover that time is harder than that. :) [1nickt]: TCLion are you parsing the dates with DateTime or another tool? [1nickt]: I note DateTime::Format:: Flexible, announced immediately below this box in the CPAN feed [Corion]: 1nickt: That one sounds sensible as it will tell you when it found an error [1nickt]: Throws on error, I believe [1nickt]: But should handle month as number or word

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (14)
As of 2017-03-23 14:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Should Pluto Get Its Planethood Back?

Results (287 votes). Check out past polls.