brooklynsweb
brooklynsweb

Reputation: 817

Preparing a variable value for display using %d in Python

GOAL:

I'm trying to display (assumed float) value as a decimal, within a print call using the '%d' operator.

PROBLEM

Documentation states that '%d' can only take the value of a decimal. Taking this into account, I imported the 'decimal' module and attempted to convert using the decimal function. The result was not altered, and my code would return what looks like a 'floored' price for my oranges (my oranges are not happy with that). What am I doing wrong?

CODE

 import decimal

    prices = {
        "banana":4,
        "apple":2,
        "orange":1.5,
        "pear":3
        }

    stock = {
        "banana":6,
        "apple":0,
        "orange":32,
        "pear":15
        }

    for x in prices:
        print x
        print "price: %d" % (decimal.Decimal(prices[x]))

        for y in stock:
            if y == x:
                print "stock: %d" % (stock[y])

RESULT

orange
price: 1 // Need this to return the price (1.5)
stock: 32
pear
price: 3
stock: 15
banana
price: 4
stock: 6
apple
price: 2
stock: 0

Upvotes: 2

Views: 3825

Answers (2)

aIKid
aIKid

Reputation: 28312

Well, here's my attempt.

The %d specifier converts the number to an integer of base 10. So when you do something like:

print "price: %d"%Decimal("1.5")

It would print price:1.

To achieve what you want, you can use the %f specifier:

print "price: %.2f"%Decimal("1.5")

See more on formatting here. Hope this helps!

Upvotes: 0

Krzysztof Kosiński
Krzysztof Kosiński

Reputation: 4335

If you want to print floating point numbers, use the %f specifier. For example, this will print the price with 2 decimal digits of precision:

print "price: %.2f" % prices[x]

See here for more documentation: http://docs.python.org/2/library/stdtypes.html#string-formatting

Upvotes: 1

Related Questions