0

I am adding a .10 (dime) to my variable Value, but when I print the updated variable it only prints out 0.1, instead of 0.10. I need to keep the zero at the end.

Value= 0.00#before this was just 0
quarter = 0.25
nickel = 0.05
dime = 0.10
if s == "quarter":
    Value= Value + quarter
    print("Value: ", "$", float(Value))
elif s == "nickel":
    Value = Value + nickel
    print("Value: ", "$", float(Value))
elif s == "dime":
    Value= Value + dime
    print("Value: ", "$", float(Value))

I am not sure why the zero goes away when the value dime gets added to value :/

Quintana
  • 1
  • 2
  • 1
    [Formatting Numbers for Printing in Python](https://blog.tecladocode.com/python-formatting-numbers-for-printing/) – Fildor Oct 09 '20 at 13:59
  • 2
    Just beware of [using floating point types for money](https://stackoverflow.com/q/3730019/10077). – Fred Larson Oct 09 '20 at 14:07

1 Answers1

1

You can use formatting to achieve this,

See the example below. I used f-string to make the print statements look neat.

Value= 0.00#before this was just 0
quarter = 0.25
nickel = 0.05
dime = 0.10

s = "dime"

if s == "quarter":
    Value= Value + quarter
    print(f"Value : ${Value:.2f}")
elif s == "nickel":
    Value = Value + nickel
    print(f"Value : ${Value:.2f}")
elif s == "dime":
    Value= Value + dime
    print(f"Value : ${Value:.2f}")

# Output": Value : $0.10

If you don't want to use f-strings, alternatively you can use format to format the floating points for you,

Value= 0.00#before this was just 0
quarter = 0.25
nickel = 0.05
dime = 0.10

s = "dime"

if s == "quarter":
    Value= Value + quarter
    print("Value : $ {:.2f}".format(Value))
elif s == "nickel":
    Value = Value + nickel
    print("Value : $ {:.2f}".format(Value))
elif s == "dime":
    Value= Value + dime
    print("Value : $ {:.2f}".format(Value))
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108