Noob to Python and new to Code in general. I "know" how to use the round function and can use it for numbers that have more then 2 decimal places. My question is how do I get numbers that only have 1 decimal place to add the zero to make it to two decimal places. Like dollar amounts for instance?
Here is something I wrote, any advice off topic or critique would be welcome. I already know my math is a bit "creative". I can guarantee there is a simpler way, but i was just making it work. And maybe if somebody could explain to me how i could use a f-string in this code that would be awesome too.
thanks
print("Welcome to the tip calculator!")
total = input("What was the total bill? ")
tip = input("How much tip would you like to give? 10, 12, or 15? ")
split = input("How many people to split the bill? ")
total_float = float(total)
tip_float = float(tip)
tip_float /= 10.00**2.00
tip_float += 1.00
split_float = float(split)
each_pay = total_float * tip_float
each_pay /= 1.00
each_pay /=split_float
each_pay_str = str(round(each_pay, 2))
print("Each person should pay: $",each_pay_str )
Something to realise is that round()
takes a float and gives you a float. So, round(1.234, 2)
would return 1.23
. However, the answer is still a float. What you're asking is about the string representation of a number, so how it appears on the screen, not the actual value. (after all, 1.
and 1.0
are really just the same value, the 0
doesn't do anything for a float)
You can do this:
print(f'{1.234:.2f}')
Or:
s = f'{1.234:.2f}'
print(s)
That also works for numbers that don't need as many digits:
print(f'{1:.2f}')
The reason this works is that the f-string is just creating a string value that represents the numerical value.