# PEP proposal for round(x,n) enhancement

Christopher Smith csmith at blakeschool.org
Mon Sep 10 23:49:07 CEST 2001

```Dear List,

It was suggested that I see what type of interest there might be in
this idea before posting it as a PEP.

***
I would like to see an additional syntax added to the round function.

At present the syntax for round is round(x,n) where n can be a float or
integer, (positive or negative) that indicates the digit to which the
number x should be rounded as measured from the one's digit:
round(12345,-2) returns 12300 while round(1.2345,2) returns 1.23.

The enhancement that I would like to see is the ability to indicate the
number of digits counting *from the 1st non-zero digit* that should be
reported.  These digits are often called the significant digits.  Both
12345 and 1.2345 when rounded to the 3rd significant digit are 12300
and 1.23 but instead of having to inspect the numbers to figure out
what digit to round them to, an argument that would be interpreted as
"the 3rd digit counting from the first non-zero digit" would do the job

***
How to add this syntax to the round function:

round(x,n) will test to see if there is a decimal portion to n.  If
there is, n will be multiplied by 10 and the integer of the resulting
value will be the number of digits to which x will be rounded.  This
can be simulated with the function Round as shown below:

####
from math import floor,log10
def Round(x,n):
if n%1:
sigdig=int(10*n)
return round(x,sigdig-1-floor(log10(abs(x))))
else:
return round(x,n)
####
Example input/output:
>>> print Round(1.23456789019,1.1) #11 digits
1.2345678902
>>> print Round(12345,.3)
12300.0
>>> print Round(1.2345,.3)
1.23

***
Anticipated problems

-the floor() portion of the solution returns a floating point value;
when implemented, this could be changed to int(floor()) to avoid
coercion issues.

-Using the syntax as stated above is the simplest way I can think to
allow for an arbitrary number of digits to be specified.  (The simplest
method which would allow for the range 1-9 would be to use the 10ths
place only.)  The only quirky thing that would be introduced with the
present proposal would be that to specify a multiple of 10 you would
have to make n=1.0x or 2.0x where 'x' specifies some digit in the
1/100ths place to create a non-zero decimal portion to the number.
This x would be lost in the conversion int(10*n).  If someone were
rounding their data, it is doubtful that they would be rounding to more
than 5 digits so this issue wouldn't arise often.

***
Open for feedback :-)

/c

Christopher P. Smith
The Blake School
Minneapolis, MN

```