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.

2

2 Answers 2

4

To round to 4 significant digits:

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

To print it as an integer:

print "%.0f" % f # -> 8830000 
Sign up to request clarification or add additional context in comments.

Comments

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 

1 Comment

It won't produce result rounded to 4 significant digits if x has different order of magnitude e.g., 123456789

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.