12,345.678 not 12345.678

Hi,

Is there any way that I can print out a number in the format 12,345.678

Thanks
Norman
Norman_SKAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
jmcgConnect With a Mentor OwnerCommented:
It takes an extra step, there's no direct formatting support. Here's what it says in the Perl FAQ:

    sub commify {
               local $_  = shift;
               1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
               return $_;
           }

           $n = 23659019423.2331;
           print "GOT: ", commify($n), "\n";

           GOT: 23,659,019,423.2331

       You can't just:

           s/^([-+]?\d+)(\d{3})/$1,$2/g;

       because you have to put the comma in and then recalculate
       your position.

       Alternatively, this commifies all numbers in a line
       regardless of whether they have decimal portions, are pre-
       ceded by + or -, or whatever:

           # from Andrew Johnson <ajohnson@gpu.srv.ualberta.ca>
           sub commify {
              my $input = shift;
               $input = reverse $input;
               $input =~ s<(\d\d\d)(?=\d)(?!\d*\.)><$1,>g;
               return scalar reverse $input;
           }
0
All Courses

From novice to tech pro — start learning today.