-1

Lets assume a Customer wants to know a price of a product, so I perform a Database query, and get the value 95 (as int) representing the value in cents. Now I want to tell the customer the price in euros, so I do that:

    print("Price: " + format(price/100, ".2f") + "EUR")

What I get printed is:

    Price: 0.00EUR

Why and how can I fix this?

Thanks

DumperJumper
  • 75
  • 11
  • Convert your variable float (now result of `price / 100` is integer). For example, `print("Price: " + format(price/100.0, ".2f") + "EUR")`. – avtomaton Dec 04 '15 at 22:41
  • When it comes to money, it's best to use `Decimal`: https://docs.python.org/3.5/library/decimal.html – Nuno André Sep 11 '16 at 00:38

3 Answers3

2

You need your output to be a float. Try dividing by 100.0

Jonathan Adelson
  • 3,275
  • 5
  • 29
  • 39
0

You have to cast to float by doing price = float(whatever) before the string format. If the numerator or denominator is a float, then the result will be also. If both are integers result will be integer.

Nuno André
  • 4,739
  • 1
  • 33
  • 46
  • This answer implies that you can do `price = float(price/100)`, which is incorrect. – Mark Ransom Dec 04 '15 at 22:39
  • No. The answer implies that you can cast ``price`` to float before the string format, when he gets ``price``. But I edited the answer, anyway. – Nuno André Dec 04 '15 at 22:40
0

This happens since price and 100 are both ints - and if you do any operations on ints, the result will be an int. When you do price/100, you get 0.95 floored to an int i.e. 0 and then format (0, ".2f") gives you 0.00. What you need to do is convert price to a float before you do any operations on it, as in format(float(price)/100, ".2f") or you can just divide by a float 100.0 instead, as in format(price/100.0, ".2f") to fix this.

Anant Jain
  • 76
  • 7