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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With