简体   繁体   中英

Formatting integers and floats inside strings in python

I'm trying to figure out how to print formatted strings rounding to significant figures. Say I have:

x = 8829834.123

And I want to print it rounded to four sig figs, as an integer. I tried:

print "%4d"%x

and I just get:

8829834

Why won't it display:

8829000?

I thought that was how string formatting worked.

To round to 4 significant digits:

f = float("%.4g" % 8829834.123)

To print it as an integer:

print "%.0f" % f
# -> 8830000

Format Specifier does not support integer rounding, there may be some solutions but not out of the Box, here are couple of them

>>> print "{:d}000".format(int(x/1000))
8829000
>>> print "{:d}".format(int(round(x,-3)))
8830000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM