sub a{$_=sprintf"%.2f",pop;{s/(\d)(\d{3})(?!\d)/$1,$2/&&redo}$_}
Abigail | [reply] [d/l] |
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 | [reply] [d/l] [select] |
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} | [reply] [d/l] [select] |
Why the need for sprintf ?? Am I missing something of importance?
If sprintf is not needed, here is one at 49 chars....
sub a{$_=pop;{s/(\d)(\d{3})(?!\d)/$1,$2/&&redo}$_.'.00'}
update: I am a little confused about the input, the post asks for an integer, which would not have any decimal places, but some of the input has a decimal place..
Should this handle input with decimal places, or should it just trust that the user submits integers only?
perl -e '$_=$0;split??;chop$_;$;=pop@_;$;++for(0..9060420);$_.=reverse
+$;;print'
| [reply] [d/l] [select] |
To get the precision correct. Your script fails if you input 1234.56.
++Abigail-II
enoch
| [reply] [d/l] |
# 48
sub f { use Number::Format':subs';format_number(pop,2,2) }
#23456789012345678901234567890123456789012345678
| [reply] [d/l] |
# 1 2 3 4 5
#2345678901234567890123456789012345678901234567890123
$_=sprintf"%.2f",pop;{s/(^\d+)(\d{3})/$1,$2/&&redo}$_
Makeshifts last the longest. | [reply] [d/l] |
| [reply] [d/l] |