2 Replies - 9058 Views - Last Post: 25 January 2009 - 08:42 PM Rate Topic: -----

#1 Jooshboy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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  Icon User is offline

  • New D.I.C Head

Reputation: 6
  • View blog
  • 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!
Was This Post Helpful? 0
  • +
  • -

#3 Jooshboy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1