0

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 )
  • 1
    Does this answer your question? [Add zeros to a float after the decimal point in Python](https://stackoverflow.com/questions/15619096/add-zeros-to-a-float-after-the-decimal-point-in-python) – Gino Mempin Nov 29 '21 at 05:36

4 Answers4

2

Use "format" function of python to add N number of decimal places

print(10.1) <------- will print 10.1

print(format(10.1,".2f")) <------- will print 10.10(.2f denotes decimals to add)

Tharu
  • 188
  • 2
  • 14
1

You can use f-string:

each_pay = 1.1
print(f"Each person should pay: ${each_pay:.2f}") # Each person should pay: $1.10

Note that you don't even need the line each_pay_str = str(round(each_pay, 2)). It is generally better to leave a number (float) as it is, and convert it only when needed. Here, f-string automatically converts it to a string.

j1-lee
  • 13,764
  • 3
  • 14
  • 26
0

You could do something like this:

x = '%.2f' % (f)

Or to make it more elegant, you could do something like this:

f'{f:.2f}'
BuhtanDingDing
  • 75
  • 1
  • 10
0

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.

Grismar
  • 27,561
  • 4
  • 31
  • 54