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?'


In reply to How to give format to numbers? by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.