Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

comment on

( [id://3333] : superdoc . print w/replies, xml ) Need Help??

It has been a while since there has been a good round of golf, so I decided to post one. I couldn't come up with a nice interesting math brain-teaser, so I'll post this one.

The Rules
  • Write a sub that takes a number as an argument and returns it in the standard monetary format -- with comma's and to two decimal places

Expected Input-Output
  • Input: 3
  • Output: 3.00

  • Input: 1000
  • Output: 1,000.00

  • Input: 12345678
  • Output: 12,345,678.00

  • Input: 4444444.11
  • Output: 4,444,444.11

  • Input: 98765.343
  • Output: 98,765.34

  • Input: 111.229
  • Output: 111.23

My Swing (83 chars)
sub a { $_=pop;($_=reverse sprintf"%.2f",$_)=~s/(\d\d\d(?=\d))/$1,/g,return re +verse split'' }


(update: Changed "integer" to "number". Integers don't have decimals. Thanks to xylus for pointing out my err.

In reply to (Golf) Formatting NumberTo Money by enoch

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

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.