页面

2008-11-17

Python Float Number Round and Format

A useful function that can round a float's significant digit(s):
def round_to_n(x, n):
"""
Rounds float x to n significant digits, in float notation (i.e. 'f', other notation: e (scientific notation), g (when digits is 6 longer, use seientific notation, otherwise float notation)).
"""
    if n < 1:
        raise ValueError("number of significant digits must be >= 1")
    return "%.*f" % (n-1, round(x, n))

没有评论: