Everything2
Near Matches
Ignore Exact
Full Text
Everything2

Perl: Converting an integer or float to currency

created by 2501

(idea) by 2501 (7.2 y) (print)   ?   (I like it!) Tue Jun 20 2000 at 0:09:58

This is a wonderful little Perl script which is very useful when dealing with monetary database output.

sub docurr($){
local($_)=shift;
$_=sprintf("%.2f",$_);
1 while s/(.*\d)(\d\d\d)/$1,$2/;
$_="\$".$_;
$_;
}


This code is a procedure which takes in one variable"$_" and makes it a float with 2 decimal places using sprintf. Next, The codelooks for an ending of 4 numbers and places a comma in the appropriate position. It continues working its way up the variable one character at a time adding commas when there is a pattern match. When no more pattern matches occur, we cat the results of our while loop with a dollar sign and return the resulting string.

syntax: $printme=&docurr($somenumber);

(idea) by neil (10.5 mon) (print)   ?   (I like it!) Tue Jun 20 2000 at 0:32:48

Of course, this code is very locale-specific. For one thing, what if the current locale uses `,' instead of `.' as the decimal separator? Then inserting commas as period separators is not a good idea. Also, what if the currency symbol is not `$'? Of course, C-style locales have their own problems; see, for example, the SECURITY section of the perllocale(1) manpage.

In addition, it loses accuracy. You don't always want to lose the ability to represent fractions of cents.


printable version
chaos

never store currency in a float Why Perl sucks $_ Perl
TheBooBooKitty confesses: my life as a teenage whore named Susan Bikini or thong? Java Financial Library Terry Pratchett
Currency of the World Somnophilia Horseshoes of a Zephyr June 20, 2000
database code
Y'know, if you log in, you can write something here, or contact authors directly on the site. Create a New User if you don't already have an account.
  Epicenter
Login
Password

password reminder
register

Everything2 Help

Cool Staff Picks
Nodes to live by:
The Warlock of Firetop Mountain
mandolin
Some Ethical Issues With The Use Of Robot Combatants
Sam and Dave
woodchipper
The Tick
Japan's 21st century crisis
Chopstick vs. Fork
The Guru got a girlfriend
Wheresoever he went, there was Eden
The Nixon-Khrushchev "Kitchen Debate"
Pinyin
hiragana
New Writeups
aneurin
Earl of Landaff(person)
Heitah
Pseudocide(idea)
XWiz
Google Knol(lede)
Mythi
July 24, 2008(personal)
locke baron
The fall of Earth(fiction)
BookReader
Fear the Cold(dream)
Pavlovna
Kathleen MacInnes(person)
stainedglass
1(fiction)
kalen
Three "T"s(idea)
octillion369
Undead(idea)
archiewood
Ico(fiction)
Heisenberg
Why I love Everything2(log)
octillion369
Death Knight(person)
XWiz
Are you hoping for a miracle?(review)
santo
The Host(review)
E2 is a by-product of the existence of The Everything Development Company