Question:
How do I format the number of decimal places of a decimal number in Python?
For example, I want to display only two decimal places of the following number:
numero_decimal = 3.141592653589793
How could I transform this number to 3.14
?
Answer:
Rounded
If rounding:
round(3.141592653589793, 2)
Which is what happens when you do something like that.
"%.2f" % 3.141592653589793
truncating
In this case, you need more care, as the lack of a dedicated function forces you to compose a manual solution.
This simple function works well in everyday life:
def trunc(num, digits):
sp = str(num).split('.')
return '.'.join([sp[0], sp[:digits]])
This one works on 2 and 3 and takes into account exponential notation, for more complex scenarios:
def truncate(f, n):
'''Truncates/pads a float f to n decimal places without rounding'''
s = '{}'.format(f)
if 'e' in s or 'E' in s:
return '{0:.{1}f}'.format(f, n)
i, p, d = s.partition('.')
return '.'.join([i, (d+'0'*n)[:n]])
Codes used from here:
Note: for those who don't know the difference:
-
When rounding
3.19999
to 2 decimals the result is3.20
; -
When truncating
3.19999
to 2 decimals the result is3.19
.