Printing floats with additional decimal places

I tagged this post with the “conditionals-control-flow-py” tag because that’s the lesson on which I am currently working, but this question is actually about formatting floats.

In this exercise (I’ll link the exercise even though you probably don’t need to see it to answer my question), I print out a float representing a dollar amount of the cost of shipping. However, the dollar amount only has one decimal place and I would like to print out a dollar amount with two decimal places since that is how money is usually represented. Would someone be able to tell me how I can print out a float with two decimal places?

Here is a function I wrote to determine the cost of shipping:

def drone_shipping(weight):
  if weight <= 2:
    return 4.50 * weight
  elif weight <= 6:
    return 9.00 * weight
  elif weight <= 10:
    return 12.00 * weight
  else:
    return 14.25 * weight
  
print(drone_shipping(7))

At the bottom of the code, you can see I printed the cost of shipping for a package that weighed 7 lbs. Here is the output I get when I print this:

84.0

How could I make the output read 84.00?

there are many ways to do this:

https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points

1 Like

@stetim94 thank you! Do you think you could provide me with an example of how to use one of these solutions in the context of the exercise I was working on? Would I do something like this:

print("{0:.2f}".format(drone_shipping(7)))

?

step 6 of this project:

Using those two functions for ground shipping cost and drone shipping cost, as well as the cost of premium ground shipping, write a function that takes one parameter, weight and prints a statement that tells the user

  • The shipping method that is cheapest.
  • How much it would cost to ship a package of said weight using this method.

we need to print a string to inform the user which shipping method is cheapest, then i would indeed use format() like you did

1 Like

@stetim94 okay, thank you very much!