Format float in Python

Asked

Viewed 3,178 times

-1

How should I show only two decimal places using the "float" in Python print('The average weight of these people is: {}'. format(media))

2 answers

0


Try:

print('O peso médio dessas pessoas é: {:.{prec}f}'.format(media, prec=2))

or, simplifying:

print('O peso médio dessas pessoas é: {:.2f}'.format(media))

0

You could use the string formatting operator for this:

    '%.2f' % 1.234
    '1.23'
    '%.2f' % 5.0
    '5.00'

The operator result is a string, so you can store it in a variable, print etc.

In the case of the use of Python 3.6 follows the syntax - the string is placed between quotes, as usual, with prefix f'... in the same way you would r'... for a raw string. So you put anything you want to put inside your string, variables, numbers, inside keys

    print('O peso médio dessas pessoas é: {a:.2f}'.format(media))

If you really want to change the number itself, instead of displaying it differently, use format ()

Format it to 2 decimal places:

    format(5.00000, '.2f')
    '5.00'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.