[Tutor] Rounding to n significant digits

Richard Wagner wagnerr at umich.edu
Wed Sep 2 03:44:00 CEST 2009


I'm fairly new to Python and am trying to find a simple way to round  
floats to a specific number of significant digits.  I found an old  
post on this list with exactly the same problem:

<http://mail.python.org/pipermail/tutor/2004-July/030268.html>
> Is there something (a function?) in Python 2.3.4 that will round a  
> result to n significant digits, or do I need to roll my own? I don't  
> see one in the math module.
>
> I mean something like rounding(float, n) that would do this:
> float = 123.456789, n = 4, returns 123.5
> float = .000000123456789, n = 2, returns .00000012
> float = 123456789, n = 5, returns 123460000
>
> Thanks,
>
> Dick Moores

And another post gave this solution:

<http://mail.python.org/pipermail/tutor/2004-July/030311.html>
> 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)

Converting to a string seemed like an awkward hack to me, so I came up  
with a mathematical solution:

> import math
>
> def round_figures(x, n):
> 	"""Returns x rounded to n significant figures."""
> 	return round(x, int(n - math.ceil(math.log10(abs(x)))))
>
> print round_figures(123.456789,4)
> print round_figures(.000000123456789,2)
> print round_figures(123456789,5)
> print round_figures(0.987,3)
> print round_figures(0.987,2)
> print round_figures(0.987,1)
> print round_figures(-0.002468,2)
>
> 123.5
> 1.2e-07
> 123460000.0
> 0.987
> 0.99
> 1.0
> -0.0025

Since the built-in round(x,n) can do rounding in the 10's and 100's  
places just as easy as 0.1's and 0.01's, my function just counts how  
many digits are in use and rounds off n digits away.

I thought others might find this solution useful.  Or somebody else  
might share a nicer way.

Richard Wagner



More information about the Tutor mailing list