0

I want to have Python declare a float variable and then display that variable to two decimal points, even if the number is an integer. For example:

def floatToMoney:
    # Some kind of function that outputs two decimal places
foo = float(6)
print(floatToMoney(foo))
boo = float(3.14159)
print(floatToMoney(boo))

and have an output of:

6.00
3.14

I know that round() can do this, but again if the number is an integer it doesn't display the decimal places. I found the decimal package, but is there any way to do this without having to import any packages?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Tiskolin
  • 167
  • 17

2 Answers2

3

I'd just use a format string:

def floatToMoney(f):
    return "%.2f" % f
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Thank you! This works. I haven't really used % in python strings before, so I don't know how they work. Could you please explain? Thank you! – Tiskolin Nov 21 '17 at 22:24
2

In Python 3.x and 2.7, you can simply do this:

>>> '${:,.2f}'.format(1234.5)
'$1,234.50'

The :, adds a comma as a thousands separator, and the .2f limits the string to two decimal places (or adds enough zeroes to get to 2 decimal places, as the case may be) at the end.

Roman Svitukha
  • 1,302
  • 1
  • 12
  • 22