Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Formating numbers with thousand separator - Solution for web-applications

by wee (Scribe)
on Jun 18, 2013 at 21:35 UTC ( [id://1039668]=note: print w/replies, xml ) Need Help??


in reply to Formating numbers with thousand separator - Solution for web-applications

That's a lot of code for what should be fairly straightforward:
my $sep = ','; my $number = '12345678.27'; print MakeThousands($number), "\n"; sub MakeThousands { local $_ = reverse(shift()); s/(\d{3})(?=\d)(?!\d*\.)/$1$sep/go; return scalar(reverse()); }
I know in Perl there's always a balance to be struck between making code clear and keeping it concise (at least for me), but when you have three times as much code to do something fairly basic, you run the risk of adding bugs through typos, having slower execution, etc. If I just want to print numbers like "12,345,678.27", why use more code than is necessary? If you abstract out the thousands separator, this shouldn't be a sub you touch more than once. Speaking of slower code, you mentioned something about performance. Your solution is roughly twice as slow as the one I have above:
Benchmark: timing 5000000 iterations of MakeThousands, Thousandformat. +.. MakeThousands: -1 wallclock secs ( 0.06 usr + 0.00 sys = 0.06 CPU) @ + 83333333.33/s (n=5000000) Thousandformat: 1 wallclock secs ( 0.12 usr + 0.00 sys = 0.12 CPU) +@ 41666666.67/s (n=5000000)
If execution speed is really your #1 concern, you might take an eye toward simplification.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2024-04-24 08:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found