Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
would come out the other side as:86902 .50 2. 165.0 0.666666666
now, i have a series of regexes that gets the job done...but its ugly and a little bruteforce-ish:86902.00 0.50 2.00 165.00 0.66
so, this works just fine, its just not every elegant and i'm a stickler for clean code. is there a better way?# 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/;
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
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 | |
|
Re: How to give format to numbers?
by Asim (Hermit) on Jun 22, 2006 at 15:02 UTC | |
|
Re: How to give format to numbers?
by Mutant (Priest) on Jun 22, 2006 at 16:49 UTC | |
|
Re: How to give format to numbers?
by Hue-Bond (Priest) on Jun 22, 2006 at 15:01 UTC |