-3

Create a function called format_currency which takes in a float as input and returns a string containing the number with a $ in front of it, with 2 decimal places.

i got no idea what i have done

def format_currency()
format("format_currency")
format_currency = float(input("Enter amount"))
print ("$" , format_currency)
  • 1
    That the function "takes in a float as input" means that the number is a parameter to the function - you should not read it from the user. That the function "returns a string" means that the function returns a string to the caller of the function - you should not print the string. If you write `money = format_currency(10.0)`, the value of `money` should be `"$10.00"`. – molbdnilo Sep 05 '19 at 07:58

4 Answers4

1

Here you go

pi = 3.1415926535
def format_currency(f):
    return '$%.2f' % f

print(format_currency(pi)) # $3.14 
Erdal Dogan
  • 557
  • 1
  • 4
  • 10
  • 1
    It doesn't really help OP to simply do their homework for them. – John Coleman Sep 05 '19 at 08:05
  • Totally agree, even if it seems like handing them the hw they are responsible for, this answer could've help another beginner looking for such a solution. It is not ethical to do, but this is what online communities are for, I believe. You are not only helping the OP when you answer a question but hundreds of people maybe. – Erdal Dogan Sep 05 '19 at 08:25
0

You can do that something like this

def formatCurrency(amount):
    return "${0:.2f}".format(amount)

amount = float(input())
print(formatCurrency(amount))
Ankit
  • 604
  • 6
  • 13
0

It's important that you validate whether the number is a float or not. Expanding on E. Dogan's answer:

def format_currency(amount):
    try:
        float(amount)
        return '$%.2f' % float(amount)
    except ValueError:
        return "Not a number"

print(format_currency(3)) # $3.00
print(format_currency(3.123)) # $3.12
print(format_currency("not a number")) # Not a number
print(format_currency("3")) # $3.00

Also check: How do I check if a string is a number (float)?

SiGm4
  • 284
  • 1
  • 2
  • 10
0

when i understand your question correct you need this

def format_currency(amount): # input argmuents are in the braces ()
    if type(amount) is float
        return f'${amount:.2f} # with return we can return values from a function
    else:
        raise ValueError("Amount must be a float")

# to use the function
money = format_currency(3.1234) # input arguments are passed in the braces ()
print("i have", money)

the f'' part is called f strings and is special syntax for format strings in Python 3.x. The thing in curly braces {} is evaluated after the double dot : you can give a format specification so here its .2f which means only 2 decimal places

Gorock
  • 391
  • 1
  • 5