Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round an answer to 2 decimal places in Python

The issue i am having is my rounding my results to 2 decimal places. My app gets the right results, however, i am having difficulty making the app round to the nearest decimal as you would with 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 6 month price is 13.799999999999999 but i want it to show 13.80

I've looked around google and how to round a number but couldn't find much help on rounding a result.

like image 808
python_newb Avatar asked Nov 19 '12 22:11

python_newb


People also ask

How do you format to two decimal places in Python?

As expected, the floating point number (1.9876) was rounded up to two decimal places – 1.99. So %. 2f means to round up to two decimal places.

How do you round decimal places in Python?

Python round() Function The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals. The default number of decimals is 0, meaning that the function will return the nearest integer.


2 Answers

You should use a format specifier:

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

Even better, you shouldn't rely on floating point numbers at all and use the decimal module 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")))
like image 157
Niklas B. Avatar answered Nov 15 '22 17:11

Niklas B.


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

format(cost, '.2f')

This function returns a string that is formated as defined in the second parameter. So if cost contains 3.1418 the code above returns the string '3.14'.

like image 36
anhoppe Avatar answered Nov 15 '22 17:11

anhoppe