Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I need to format any of these formats of numbers to a decimal with two places (#.00)...so these numbers:
86902 .50 2. 165.0 0.666666666
would come out the other side as:
86902.00 0.50 2.00 165.00 0.66
now, i have a series of regexes that gets the job done...but its ugly and a little bruteforce-ish:
# if value is '#' then append ".00" $curr .= ".00" if $curr =~ m/^\d+$/; # if value is '.#' then prepend "0" $curr = "0".$curr if $curr =~ m/^\.\d+$/; # if value is '#.' then append "00" $curr .= "00" if $curr =~ m/^\d+\.$/; # if value is '#.0' then append "0" $curr .= "0" if $curr =~ /^\d+\.\d$/; # if necessary, truncate to 2 decimal places $curr =~ s/^(\d+\.\d{2})\d+$/$1/;
so, this works just fine, its just not every elegant and i'm a stickler for clean code. is there a better way?

also, if theres an easy way to round to rather than truncate to 2 decimal places (so i'd get 0.67 instead of 0.66), by all means let me know!

2006-06-23 Retitled by planetscape, as per Monastery guidelines

( keep:0 edit:13 reap:0 )

Original title: 'a *cleaner* way to do it?'

Replies are listed 'Best First'.
Re: How to give format to numbers?
by ikegami (Patriarch) on Jun 22, 2006 at 15:00 UTC
Re: How to give format to numbers?
by philcrow (Priest) on Jun 22, 2006 at 15:01 UTC
    I'd use sprintf:
    my $num = 5.26256; my $formatted = sprintf( "%.2f", $num ); print "$formatted\n";
    Phil
Re: How to give format to numbers?
by Asim (Hermit) on Jun 22, 2006 at 15:02 UTC
    format any of these formats of numbers to a decimal with two places (#.00)

    printf and it's good friend sprintf were born to do your bidding along these lines, my friend. I'd recommend a good, long look at perlfaq4; it touches upon this issue, as well as your rounding problems.

    Good luck!

    Edited for quick grammar cleanup...

    ----Asim, known to some as Woodrow.

Re: How to give format to numbers?
by Mutant (Priest) on Jun 22, 2006 at 16:49 UTC
    As mentioned, sprintf/printf may suit your needs.

    Another option is Number::Format, which will do all that, and a lot more.
Re: How to give format to numbers?
by Hue-Bond (Priest) on Jun 22, 2006 at 15:01 UTC

    You want printf:

    while (<DATA>) { printf "%1.2f\n", $_; } __DATA__ 86902 .50 2. 165.0 0.666666666

    Update: Better sprintf, as has been pointed out

    --
    David Serrano