# format as currency function

Page 1 of 1

## 2 Replies - 11421 Views - Last Post: 25 January 2009 - 08:42 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=82631&amp;s=58834e55bdcd9b0c3a89595b2f18a1a6&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Jooshboy

Reputation: 0
• Posts: 3
• Joined: 05-January 08

# format as currency function

Posted 24 January 2009 - 10:56 PM

While writing a program for school I wanted to format some values as currency in python, so after a couple of hours looking through the interwebs with no success i decided to create my own, so here it is

```
def currency(number, isPercent):
#trunkates the 'number' variable to the 100's place
base = int(number)
remain = number - base
decStep = remain*100
decimal = int(decStep)
decimal = float(decimal)
decimal = decimal/100
money = base + decimal
money = str(money)
#conditional that adds an additonal '0' to the number if the decimal
# only goes to  the 10's place
zeroChk = remain *10
if zeroChk == int(zeroChk):
money = money + "0"
#conditional that will put in a dollar sign '\$' if requested by making
# isPercent equal to zero, and insert a '%' if isPercent equals 1
if isPercent == 0:
#money = str(money)
money = "\$" + money
elif isPercent == 1:
#money = str(money)
money = money + "%"
return money

```

as you may have noticed the 'isPercent' variable doesn't really have to do with currency, but the way i was using it, it made the function a little more useful. if 'isPercent' is equal to 1 then instead of '\$' before the number, it prints a '%' after the number, and if 'isPercent' is equal to 0 then the opposite is true, and if it is neither it doesn't print a '\$' or '%'

I hope this helps =D

oh and btw, if there is a currency function built into python, what is it?

Is This A Good Question/Topic? 0

## Replies To: format as currency function

### #2 Stutzbach

Reputation: 6
• Posts: 29
• Joined: 06-July 08

## Re: format as currency function

Posted 25 January 2009 - 12:22 PM

There isn't a built-in currency formatter, however you may be interested in the decimal module which will let you set the number of decimal places more easily.

In the documentation for the decimal module, they do have a currency formatter as an example.

Hope that helps!

### #3 Jooshboy

Reputation: 0
• Posts: 3
• Joined: 05-January 08

## Re: format as currency function

Posted 25 January 2009 - 08:42 PM

Thanks a bunch, I'll definitely have to browse through all that stuff. I just started programming in python the beginning of this quarter, and even though its restrictions can get a little frustrating is seems like fun =D