How to round to 2 decimals with Python?
You can use the round
function, which takes as its first argument the number and the second argument is the precision after the decimal point.
In your case, it would be:
answer = str(round(answer, 2))
How to round to two decimal places in python?
You missplaced the %.2
:
tax = (round(subtotal * 0.0475, 2))
And you don't need the %.
round down to 2 decimal in python
Seems like you need the floor
:
import math
math.floor(a * 100)/100.0
# 28.26
Round up to 2 decimal in Python
The Decimal class, quantize() method, and ROUND_HALF_UP rule from the decimal module can handle this:
from decimal import Decimal, ROUND_HALF_UP
var_1 = 14.063 # expected = 14.06
var_2 = 10.625 # expected = 10.63
# a Decimal object with an explicit exponent attribute/property (to be interpreted by quantize)
Two_places = Decimal("1e-2")
for var in [var_1, var_2]:
rounded = Decimal(var).quantize(Two_places, rounding=ROUND_HALF_UP)
print(f"decimal: {rounded}")
print(f"float: {float(rounded)}")
and I get:
decimal: 14.06
float: 14.06
decimal: 10.63
float: 10.63
Keep in mind that when you're dealing with floats, you're always manipulating a less-than-precise representation of what you probably (naturally) have in mind:
Decimal(1.65) # Decimal('1.649999999999999911182158029987476766109466552734375')
Decimal('1.65') # Decimal('1.65')
In the first case, 1.65 was first turned into an IEEE-754 float, which has precision errors going from base-10 to base-2, then passed to Decimal. In the second case, Decimal interpreted the number as "one, and 65 100-ths" which equates to "165 times 10 raised to the minus 2", or 165e-2.
round up/down float to 2 decimals
Have you considered a mathematical approach using floor
and ceil
?
If you always want to round to 2 digits, then you could premultiply the number to be rounded by 100, then perform the rounding to the nearest integer and then divide again by 100.
from math import floor, ceil
def rounder(num, up=True):
digits = 2
mul = 10**digits
if up:
return ceil(num * mul)/mul
else:
return floor(num*mul)/mul
How to round a Python Decimal to 2 decimal places?
Since Python 3.3 you can use round()
with a Decimal
and it will return you a Decimal
:
>>> from decimal import Decimal
>>> round(Decimal('3.14159265359'), 3)
Decimal('3.142')
See details in this answer.
Related Topics
How to Install Writable Shared and User Specific Data Files with Setuptools
How to Print a Variable Name in Python
What Are the Risks of Running 'Sudo Pip'
What Are "Named Tuples" in Python
Live Output from Subprocess Command
Class Method Differences in Python: Bound, Unbound and Static
Http Requests and JSON Parsing in Python
Python Windows Authentication Username and Password Is Not Working
Using Python Subprocess.Call() to Launch an Ncurses Process
How to Add File Extensions Based on File Type on Linux/Unix
Apply Function to Each Element of a List
Your CPU Supports Instructions That This Tensorflow Binary Was Not Compiled to Use: Avx Avx2