PEP proposal for round(x,n) enhancement

Chris Barker chrishbarker at
Thu Sep 13 00:15:45 CEST 2001

Markus Schaber wrote:
> The problem is that you can't store this information in a floating
> point number. I just tried the following:
> >>> 0.2
> 0.20000000000000001
> This, I give the number with 1 significant digit, and end up having
> displayed 17 "significant" digits.

This is irrelevent: Python uses native binary floating point arithmetic.
That 17 digit number is the best 17 digit decimal approximation to the
best binary approximation to the rational number one fifth. (follow

The first 16 digits are exact, which is pretty darn good, if you ask me.
Python will always store floats using all the digits in the internal
representation (and may or may not display them , depending on how they
are displayed). That does not mean that thoe digit are "significant"
whcih is the whole point of this thread. I you input that number,
knowing that it only has one significant digit (or ten, whatever), it
would be nice to have a way to get your final result rounded to that
many digits. It is a handy practice to carry as many digits as possible
while doing internal calculations, so you wouldn't want Python to rouond
them for you. 

Anyway, here is a start of a function that would do what was asked for:

def sig_fig_round(x,digits):
    from math import log10, floor
    if digits <= 0:
        raise ValueError, "digits must be an integer greater than 0"
    if x == 0:
        return x
        exp = floor(log10(x))
        return round(x *

X = 123456789.
for shift in range(0,12,3):
    x = X / 10**shift
    for n in range(1,8,2):
        print x, " rounded to ", n, " significant figures is:

Christopher Barker,
ChrisHBarker at                 ---           ---           --- ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------

More information about the Python-list mailing list