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))
Rounding to the second decimal place in python
You can use the built-in round
function to round a number to up to 2 decimal places. Seems like you only need to include this in the milesToKilometers
and kilometers to miles
functions.
def milesToKilometers(miles):
mileConverstion = miles * 1.60934
return round(mileConverstion, 2)
def kilometersToMiles(kilometers):
kilometerConverstion = kilometers * 0.621371
return round(kilometerConverstion, 2)
Note: If you want the output to keep the trailing zeros e.g. 2.10
, you need to convert it into a string as numerical values omit trailing zeros. You can convert to a string like this:with_decimals = f'{round(number, 2):.2f}'
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 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
round down to 2 decimal in python
Seems like you need the floor
:
import math
math.floor(a * 100)/100.0
# 28.26
How to round each item in a list of floats to 2 decimal places?
"%.2f"
does not return a clean float. It returns a string representing this float with two decimals.
my_list = [0.30000000000000004, 0.5, 0.20000000000000001]
my_formatted_list = [ '%.2f' % elem for elem in my_list ]
returns:['0.30', '0.50', '0.20']
Also, don't call your variable list
. This is a reserved word for list creation. Use some other name, for example my_list
.If you want to obtain [0.30, 0.5, 0.20]
(or at least the floats that are the closest possible), you can try this:
my_rounded_list = [ round(elem, 2) for elem in my_list ]
returns:[0.29999999999999999, 0.5, 0.20000000000000001]
Round float to x decimals?
Use the built-in function round()
:
In [23]: round(66.66666666666,4)
Out[23]: 66.6667
In [24]: round(1.29578293,6)
Out[24]: 1.295783
help on round()
:round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0
digits). This always returns a floating point number. Precision may
be negative.
Related Topics
When to Use Get, Get_Queryset, Get_Context_Data in Django
Selecting Across Multiple Columns with Python Pandas
How to Compare Times of the Day
Stop Matplotlib Repeating Labels in Legend
How May I Override the Compiler (Gcc) Flags That Setup.Py Uses by Default
String with 'F' Prefix in Python-3.6
How to Ignore Hidden Files Using Os.Listdir()
Memory Error When Using Pandas Read_Csv
Does Python Evaluate If's Conditions Lazily
How to Set Selenium Python Webdriver Default Timeout
How to Include Image Files in Django Templates
How Do Threads Work in Python, and What Are Common Python-Threading Specific Pitfalls
Django: Adding "Nulls Last" to Query
Opencv Python: Draw Minarearect ( Rotatedrect Not Implemented)
How to Get Millisecond and Microsecond-Resolution Timestamps in Python