[Tutor] Rounding a float to n significant digits

Dick Moores rdm at rcblue.com
Tue Nov 28 08:19:28 CET 2006


I just dug this Tim Smith creation out of the Tutor archive.

def round_to_n(x, n):
	"""
	Rounds float x to n significant digits, in scientific notation.
	Written by Tim Peters. See his Tutor list post of 7/3/04 at
	http://mail.python.org/pipermail/tutor/2004-July/030324.html
	"""
	if n < 1:
		raise ValueError("number of significant digits must be >= 1")
	return "%.*e" % (n-1, x)

Thought others might find it of use.

Dick Moores



More information about the Tutor mailing list