20
How do I format the number of decimals 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 turn that number to 3.14
?
20
How do I format the number of decimals 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 turn that number to 3.14
?
34
If round:
round(3.141592653589793, 2)
Which is what happens when you do something like this.
"%.2f" % 3.141592653589793
In this case it already needs more care, because the lack of a dedicated function requires composing a manual solution.
This simple function meets well in everyday life:
def trunc(num, digits):
sp = str(num).split('.')
return '.'.join([sp[0], sp[:digits]])
This one works in 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 harnessed from here:
Note: for those who don’t know the difference:
Rounding up 3.19999
to 2 decimals the result is 3.20
;
By truncating3.19999
to 2 decimals the result is 3.19
.
9
In Python 3 has a new feature that makes this task much easier, is the .format()
that you will use when printing the result on the screen.
To print your comado with only 2 decimal places just do the following:
pi = 3.141592653589793
print('O valor de pi formatado é {:.2f}'.format(pi))
I first assigned pi to a float variable and then printed with the .format
saying he wanted 2 decimal places after the comma.
Another way is to use the f strings that allow you to do everything necessary inside the print itself and without the format
(I prefer this way).
pi = 3.141592653589793
print(f'O valor de pi formatado é {pi:.2f}')
6
Another way to format in a very similar way is with f-Strings:
pi = 3.141592653589793
print(f'O resultado de PI é {pi:.2f}')
Note the use of 'f' before the message that will come and also the variable 'pi' that goes directly inside the keys along with the formatting of 2 decimal places after the comma
3
I did using the round
.
Example:
A = 3/9
valor = round(A,3)
print (valor)
Or you can do straight:
A = round(3/9,3)
print (A)
Being the 3 the amount of decimal places you want to keep.
1
To make truncation a simple way:
n1= 1.9999999999999
t =3 # Numero de casas
d = int(n1 * 10**t)/10**t
print('Truncado', d)
print('Arredondado', round(n1,t))
Browser other questions tagged python float
You are not signed in. Login or sign up in order to post.