Round answer to 2 decimal places in Python

The problem I am facing comes down to rounding my results to two decimal places. My application gets the correct results, however, I have difficulty rounding the application to the nearest decimal, as with the currency

cost = input("\nEnter the 12 month cost of the Order: ") cost = float(cost) print("\n12 Month Cost:", cost * 1,"USD") print("6 Month Cost:", cost * 0.60,"USD") print("3 Month Cost:", cost * 0.36,"USD") 

so, for example, if the 12-month price is $ 23, the price for 6 months is 13.799999999999999, but I want it to show 13.80

I looked at google and how to round a number, but could not find much help in rounding the result.

+6
source share
4 answers

You must use the format specifier:

 print("6 Month Cost: %.2fUSD" % (cost * .6)) 

Even better, you should not rely on floating point numbers at all and use decimal instead, which gives you arbitrary precision and much more control over the rounding method:

 from decimal import Decimal, ROUND_HALF_UP def round_decimal(x): return x.quantize(Decimal(".01"), rounding=ROUND_HALF_UP) cost = Decimal(input("Enter 12 month cost: ")) print("6 Month Cost: ", round_decimal(cost * Decimal(".6"))) 
+10
source

The classic way is to multiply by 100, add 0.5 (this is a round) and int () the result. Now that you have the number of rounded cents, divide by 100 again to return the rounded swimming.

 cost = 5.5566 cost *= 100 # cost = 555.66 cost += 0.5 # cost = 556.16 cost = int(cost) # cost = 556 cost /= float(100) # cost = 5.56 cost = 5.4444 cost = int(( cost * 100 ) + 0.5) / float(100) # cost = 5.44 
+2
source

If you just want to have it as a string, the format may help:

 format(cost, '.2f') 

This function returns a string that is formed as defined in the second parameter. Therefore, if the value contains 3.1418, the code above returns the string "3.14".

+2
source

If you just want it to print, line formatting will work:

 print("\n12 Month Cost:%.2f USD"%(cost*1)) 
+1
source

All Articles