xxxxxxxxxx
# Basic syntax:
format(your_number, '.4f')
# Note, at first I tried the round() syntax like this:
round(your_number, number_decimals)
# but it didn't keep a consistent number of decimals. For example, if I wanted
# to keep 4 decimals in case where I have 5 significant digits, this would
# return:
round(3.99999, 4)
--> 4.0
# Note, the ChatGPT thread I linked to compares format() vs str.format() and
# describes some of the ways values can be formatted.
xxxxxxxxxx
>>> x = 13.949999999999999999
>>> x
13.95
>>> g = float("{0:.2f}".format(x))
>>> g
13.95
>>> x == g
True
>>> h = round(x, 2)
>>> h
13.95
>>> x == h
True
xxxxxxxxxx
floatNumber = 2.13400
#Method 1: use f-strings
print(f"{floatNumber:.5f}") #Output: 2.13400 == '%.5f'%floatNumber
#Method 2: use round
print(round(floatNumber,5)) #Output: 2.134
xxxxxxxxxx
def roundTraditional(val,digits):
return round(val+10**(-len(str(val))-1), digits)