in reply to Re: formatting numbers
in thread formatting numbers

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.

Replies are listed 'Best First'.
Re^3: formatting numbers
by GrandFather (Saint) on Nov 08, 2007 at 03:39 UTC

    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