Adventures | Notes

Perl - Commas in Numbers

by Derek—2004.09.14 @ 2102

Problem

Every once-in-a-while I want to output a number with commas in the right place — a more “human-readable” format: 1,359,220. Although I’ve found a few solutions, I keep losing (or forgetting) how to do it — probably because I never learned myself, just copied. Now, I’m writing these solutions down for easier access (especially when I’m without my O’Reilly books).

Solution

  1. Reverse the string so you can use backtracking to avoid substitution in the fractional part of the number. Then use a regular expression to find where you need commas, and substitute them in. Finally, reverse the string back.

    sub commify {
        my $text = reverse $_[0];
        $text =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g;
        return scalar reverse $text;
    }
    
  2. Regex to put commas in-place using a nifty while loop.

    sub commafy {
        my $thing = shift;
        1 while ( $thing =~ s/^([-+]?\d+)(\d{3})/$1,$2/ );
        return $thing;
    }