Search code examples
perl

Perl printf to use commas as thousands-separator


Using awk, I can print a number with commas as thousands separators.
(with a export LC_ALL=en_US.UTF-8 beforehand).

awk 'BEGIN{printf("%\047d\n", 24500)}'

24,500

I expected the same format to work with Perl, but it does not:

perl -e 'printf("%\047d\n", 24500)'

%'d

The Perl Cookbook offers this solution:

sub commify {
    my $text = reverse $_[0];
    $text =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g;
    return scalar reverse $text;
}

However I am assuming that since the printf option works in awk, it should also work in Perl.


Solution

  • The apostrophe format modifier is a non-standard POSIX extension. The documentation for Perl's printf has this to say about such extensions

    Perl does its own "sprintf" formatting: it emulates the C function sprintf(3), but doesn't use it except for floating-point numbers, and even then only standard modifiers are allowed. Non-standard extensions in your local sprintf(3) are therefore unavailable from Perl.

    The Number::Format module will do this for you, and it takes its default settings from the locale, so is as portable as it can be

    use strict;
    use warnings 'all';
    use v5.10.1;
    
    use Number::Format 'format_number';
    
    say format_number(24500);
    

    output

    24,500