Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting display of numbers in Python 3

I am wondering how to truncate numbers in Python 3? For example, 87.28197 to 87.281 The standard in Python 2 was using % but this is no longer used.

like image 425
Mat.S Avatar asked Jan 22 '26 10:01

Mat.S


1 Answers

The % string formatter still is available in Python 3. It is preferred you use the ''.format() string formatting syntax, which also supports specifying float precisions.

Both of these work:

>>> yournumber = 87.28197
>>> "{0:.3f}".format(yournumber)
'87.282'
>>> "%.3f" % yournumber
'87.282'

If it is just the one float you are converting to a string, then the format() function is probably more convenient as you do not need to use a {0:..} placeholder:

>>> format(yournumber, '.3f')
'87.282'
like image 138
Martijn Pieters Avatar answered Jan 25 '26 01:01

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!