in reply to Numbers aren't averaging correctly

That was actually "correct", 12/5=2.4, and 22/5 = 4.4.

Only digits before commas are converted.

use strict; use warnings; while (my $line = <DATA>) { $line =~ s/,//g; my @n = split(/\s+/, $line); my $sum = 0; for (@n) {$sum += $_}; print $sum / ($#n + 1), "\n"; } __DATA__ 2,800 2,900 3,000 3,000 2,988 5,000 5,495 4,999 4,995 4,900

This gives:

2937.6 5077.8

Replies are listed 'Best First'.
Re^2: Numbers aren't averaging correctly
by radiantmatrix (Parson) on Oct 06, 2005 at 17:55 UTC
    Instead of $line =~ s/,//g; to remove commas, I would use a more generalized regex (but on each element, not on each line):
    $elem =~ s/[^\d+-e.]//g;

    This will remove any char that is not a digit, a +, a -, an 'e' (for numbers like 2e+31), or a point (.).

    Or, even better, use Number::Format:

    use Number::Format; $elem = unformat_number($elem);

    This is especially useful if an array is used instead of the $se# notation. You'd access each one through $se[#] instead, and you could do this:

    for (@se) { $_ = $unformat_number($_) }
    <-radiant.matrix->
    A collection of thoughts and links from the minds of geeks
    The Code that can be seen is not the true Code
    "In any sufficiently large group of people, most are idiots" - Kaa's Law