Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Re: (Golf) Formatting Integer To Money

by dpuu (Chaplain)
on Aug 29, 2002 at 17:41 UTC ( [id://193837]=note: print w/replies, xml ) Need Help??


in reply to Re: (Golf) Formatting Integer To Money
in thread (Golf) Formatting NumberTo Money

49 Characters:
sub a{$_=sprintf"%.2f",pop;while(s/\B\d{3}\b/,$&/){}$_}
Update: 48 characters:
sub a{$_=sprintf"%.2f",pop;{s/\B\d{3}\b/,$&/&&redo}$_}
--Dave

Replies are listed 'Best First'.
Re: Re: Re: (Golf) Formatting Integer To Money
by thelenm (Vicar) on Aug 29, 2002 at 18:45 UTC
    Here's a 44 with a few small improvements to yours:
    sub a{$_=sprintf"%.2f",@_;1while s/\B...\D/,$&/;$_}
    It seems that the sprintf solutions fail sometimes in rounding, e.g. "123456789012345.125" becomes "123,456,789,012,345.12" instead of "123,456,789,012,345.13".

    Update: I was just informed by thospel++ that IEEE rounding is toward even, not upward. That explains the behavior, though I'm not sure if it's the desired behavior for this problem.

    -- Mike

    --
    just,my${.02}

      Actually, this is the expected rounding. If you think about it, only half of them should round up (and the other half down) since that will give a more accurate average. In this case .125 rounds down, if you try .135 it will round up and .145 will round down.
         larryk                                          
      perl -le "s,,reverse killer,e,y,rifle,lycra,,print"
      

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://193837]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2024-09-10 19:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The PerlMonks site front end has:





    Results (6 votes). Check out past polls.

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.