in reply to formatting numbers

A simplistic version is:

use warnings; use strict; for (qw($100000000.00 $100.00 $1000.00)) { my $value = reverse $_; $value =~ s/(\d{3})(?=\d)/$1,/g; $value = reverse $value; print "$_ => $value\n"; }

Prints:

$100000000.00 => $100,000,000.00 $100.00 => $100.00 $1000.00 => $1,000.00

However that (as you can see) doesn't obey the convention that $1000.00 does not get a comma.


Perl is environmentally friendly - it saves trees

Replies are listed 'Best First'.
Re^2: formatting numbers
by Anonymous Monk on Nov 08, 2007 at 03:20 UTC
    Is there a way to do this with sprintf, since I already format the number with it, like this:

    my $_accountBalance = $_db->{acct_bal}; print qq~Current Account Balance: ~ . sprintf('$%.2f', $_accountBalanc +e) . qq~! As of $_date~;


    When I used that code to format the number without the sprintf, it put the commas in the correct position, but after I got the correct format then used my sprintf it truncated everything down to 3 digits and the .xx

    Thanks again.

      Do the formatting in a sub:

      use warnings; use strict; print "Current Account Balance: ", asDollars ($_), "\n" for 100000000, 100, 1000; sub asDollars { my $value = reverse sprintf '$%.2f', shift; $value =~ s/(\d{3})(?=\d)/$1,/g; return scalar reverse $value; }

      Prints:

      Current Account Balance: $100,000,000.00 Current Account Balance: $100.00 Current Account Balance: $1,000.00

      Note that scalar is required in the return statement because reverse may otherwise see a list context.


      Perl is environmentally friendly - it saves trees