[Tutor] Rounding to n significant digits?
rdm at rcblue.com
Sat Jul 3 03:11:03 EDT 2004
At 20:18 7/2/2004, Tim Peters wrote:
> > ...
> > No, the 3 examples I gave are exactly what I want:
> > float = 123.456789, n = 4, returns 123.5
> > float = .000000123456789, n = 2, returns .00000012
> > float = 123456789, n = 5, returns 123460000
>I expect the easiest way to do this in Python is to convert to string
>using an %e format, then convert that back to float again. Like this:
>def round_to_n(x, n):
> if n < 1:
> raise ValueError("number of significant digits must be >= 1")
> # Use %e format to get the n most significant digits, as a string.
> format = "%." + str(n-1) + "e"
> as_string = format % x
> return float(as_string)
>print round_to_n(123.456789, 4)
>print round_to_n(.000000123456789, 2)
>print round_to_n(123456789, 5)
>Be sure to the read the appendix on floating-point issues in the
>Python Tutorial too! You clearly have decimal digits in mind, but
>that's not how your computer's floating-point hardware works. The
>appendix talks about the consequences of that.
*That* is beautiful. Thank you! And the appendix you mentioned is
But I realize that I don't need to return a float. Just the string will
do. Therefore, this revision of your function will do exactly what I was
thinking of, even if I didn't say so:
def round_to_n(x, n):
if n < 1:
raise ValueError("number of significant digits must
be >= 1")
# Use %e format to get the n most significant digits, as a
format = "%." + str(n-1) + "e"
as_string = format % x
print round_to_n(123.456789, 4)
print round_to_n(.000000123456789, 2)
print round_to_n(123456789, 5)
1.2346e+008 (this is much better than getting the ".0" of 123460000.0,
which implies accuracy to 10 significant digits instead of 5.)
More information about the Tutor