Josh
Josh

Reputation: 3

string to float function error using csv.dictreader

I'm using the following 2-row csv file as an inital test..

milk_price_per_cup,cream_price_per_cup,sugar_price_per_cup,vanilla_extract_price_per_cup,

0.70,1.65,1.0,30,

Then trying to run the following code:

import csv

input_file = csv.DictReader(open("ingredient_prices.csv"))

milk_price = None
cream_price = None
sugar_price = None
vanilla_price = None


for row in input_file:
    milk_price = float(row["milk_price_per_cup"])
    cream_price = row["cream_price_per_cup"]
    sugar_price = row["sugar_price_per_cup"]
    vanilla_price = row["vanilla_extract_price_per_cup"]  


    print "The milk price is %d, the cream price is %s, the sugar price is %s, and the vanilla price is %s." % (milk_price, cream_price, sugar_price, vanilla_price)

Unfortunately the output for the milk price is NOT a float... it comes out as just 0 instead of 0.7.... whats going on here? Using Python 2.7.6

Upvotes: 0

Views: 239

Answers (1)

karthikr
karthikr

Reputation: 99650

%d in string formatting is for integer decimal. If you wan float, you should be using %f

Read more on string formatting options here

Upvotes: 3

Related Questions