3

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.

Ocaso Protal
  • 19,362
  • 8
  • 76
  • 83
Logan Shire
  • 5,013
  • 4
  • 29
  • 37
  • Have a look at this question: http://stackoverflow.com/questions/3348825/how-to-round-integers-in-python. You could consider the use of round() as mentioned in the accepted answer. – Bharat Dec 17 '12 at 07:02
  • possible duplicate? http://stackoverflow.com/questions/9415939/how-can-i-print-many-significant-figures-in-python – Drew Verlee Dec 17 '12 at 07:02

2 Answers2

4

To round to 4 significant digits:

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

To print it as an integer:

print "%.0f" % f
# -> 8830000
jfs
  • 399,953
  • 195
  • 994
  • 1,670
2

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
Abhijit
  • 62,056
  • 18
  • 131
  • 204
  • It won't produce result rounded to 4 significant digits if `x` has different order of magnitude e.g., `123456789` – jfs Dec 17 '12 at 07:37