Hee Ra Choi
Hee Ra Choi

Reputation: 113

Python - Find the dollar and cent

Assume that price is an integer variable whose value is the price (in US currency) in cents of an item. Write a statement that prints the value of price in the form "X dollars and Y cents" on a line by itself. So, if the value of price was 4321, your code would print "43 dollars and 21 cents". If the value was 501 it would print "5 dollars and 1 cents". If the value was 99 your code would print "0 dollars and 99 cents".

I have done like this:

print (price/100,"dollars and",price%100, "cents")

Result Ex: 2314

23.14 dollars and 14 cents

How can I make the result look like:

23 dollars and 14 cents

Upvotes: 2

Views: 12863

Answers (3)

CopyPasteIt
CopyPasteIt

Reputation: 574

The OP was on the right track; in Python 3+ both

print (price//100,"dollars and",price%100, "cents")

and

print (math.floor(price/100),"dollars and",price%100, "cents")

give the desired result.


Here is a direct string handling attack that incorporates testing tactics:

#--------*---------*---------*---------*---------*---------*---------*---------*
# Desc: Print Dollars and Cents
#--------*---------*---------*---------*---------*---------*---------*---------*

def formatPrint(cents):
    centsStr = str(cents)
    d, c = centsStr[:-2], centsStr[-2:]
    if cents > 99:
        print(d + ' dollars and ' + c + ' cents')
    else:
        print('0 dollars and ' + c + ' cents')
    return 


x = [0,7,23,111,4321,54321]

for ndx in range(0, len(x)):
    print (x[ndx], ':')
    formatPrint(x[ndx])

Upvotes: 0

Kiba
Kiba

Reputation: 1

You can use:

price=2314

print (price/100,"dollars and",price%100, "cents")

This will output:

(23, 'dollars and', 14, 'cents')

Upvotes: 0

Yohan de Rose
Yohan de Rose

Reputation: 154

Input:

x = 4321

print (x/100),'dollars and',int(100*((x/100.00)-(x/100))),'cents'

Output:

43 dollars and 21 cents

Upvotes: 1

Related Questions