1

I have two columns, which are unit price and quantity (through input by user) and I have to multiply them together to get the total price.

price="{:0.2f}".format(float(input("Enter price: ")))
quantity=int(input("Enter quantity: "))
print("Enter expired date: ")
year = int(input('Enter a year'))
                            
                            
month = int(input('Enter a month'))
            
day = int(input('Enter a day'))
expired_date = datetime.date(year, month, day)
       
df1 = pd.DataFrame(data=[[name,price,quantity,expired_date,today<=expired_date]],columns=["Name","Unit Price","Quantity","Expiry Date","Expired?"])
            

df = df.append(df1,ignore_index=True)
            
**df['Price'] = (df["Quantity"]*(df["Unit Price"]))**
            
df["Expired?"] = df["Expired?"].replace({True: 'Yes', False: 'No'})

However, the result I get is as follows:

Unit Price   Quantity     Price 
  2.00       2            2.002.00

What is the solution for this?

nikeros
  • 3,302
  • 2
  • 10
  • 26
ineedmoney
  • 63
  • 7

3 Answers3

0

You should not format your price as a string, here:

price = "{:0.2f}".format(float(input("Enter price: ")))

Just leave

price = float(input("Enter price: "))

and that should handle your multiplication correctly

nikeros
  • 3,302
  • 2
  • 10
  • 26
  • thanks. does it mean i have to use apply function for the dataframe to show only 2 decimal places?or is there another cleaner/shorter way? – ineedmoney Jan 08 '22 at 10:29
  • @ineedmoney there are different ways you can achieve that, I personally prefer the approach described [here](https://stackoverflow.com/questions/20937538/how-to-display-pandas-dataframe-of-floats-using-a-format-string-for-columns) – nikeros Jan 08 '22 at 10:31
0

You are passing the unit price as a string in the dataframe. You need to convert it to float.

price = float("{:0.2f}".format(float(input("Enter price: "))))

or you can simply ignore format and use float as well

price = float(input("Enter price: "))
0

Firstly you should not treat your price in the string format.

But if you are doing so, cast it to float again:

price="{:0.2f}".format(float(input("Enter price: ")))
price = float(price)

This way you will get a proper output:

Enter price: 2
Enter quantity: 2
Enter expired date: 
Enter a year2022
Enter a month10
Enter a day1
      Name  Unit Price  Quantity Expiry Date Expired?  Price
0  product         2.0         2  2022-10-01      Yes    4.0