How to limit decimal numbers in Python?

8

How do I format a decimal number in Python for a given amount?

For example, I want to display only two decimal places of the following number:

numero_decimal = 3.141592653589793

How could I turn this number to 3.14 ?

    
asked by anonymous 09.01.2017 / 19:51

2 answers

14

Rounding

If it's rounding:

round(3.141592653589793, 2)

What happens when you do something like this.

"%.2f" % 3.141592653589793


Truncating

In this case you need more care, because the lack of a dedicated function forces you to compose a manual solution.

This simple function caters well day by day:

def trunc(num, digits):
   sp = str(num).split('.')
   return '.'.join([sp[0], sp[:digits]])

This one works at 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 taken from here:

  

link

Note: for those who do not know the difference:

  • When rounding 3.19999 to 2 decimals result is 3.20 ;

  • By truncating 3.19999 to 2 decimals the result is 3.19 .

09.01.2017 / 19:52
3

In Python 3 you have a new feature that makes this task much easier, it is the .format() you will use when you start the output on the screen.

To start your comma with only 2 decimal places just do the following:

pi = = 3.141592653589793
print('numero_decimal = {:.2f}'.format(pi))

I first assigned pi to a float variable and then printit with .format saying that I wanted 2 float houses after the comma.

    
07.11.2017 / 03:51