]> granicus.if.org Git - python/commitdiff
Implement round() slightly different, so that for negative ndigits no
authorGuido van Rossum <guido@python.org>
Sat, 9 May 1998 14:42:25 +0000 (14:42 +0000)
committerGuido van Rossum <guido@python.org>
Sat, 9 May 1998 14:42:25 +0000 (14:42 +0000)
additional errors happen in the last step.  The trick is to avoid
division by 0.1**n -- multiply by 10.0**n instead.

Python/bltinmodule.c

index fd31405733d29d9a0063c1780690f825f63e6775..68a5109660262e236bdf91e6a29e33e6603cbf41 100644 (file)
@@ -1488,14 +1488,22 @@ builtin_round(self, args)
        if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits))
                        return NULL;
        f = 1.0;
-       for (i = ndigits; --i >= 0; )
+       i = abs(ndigits);
+       while  (--i >= 0)
                f = f*10.0;
-       for (i = ndigits; ++i <= 0; )
-               f = f*0.1;
+       if (ndigits < 0)
+               x /= f;
+       else
+               x *= f;
        if (x >= 0.0)
-               return PyFloat_FromDouble(floor(x*f + 0.5) / f);
+               x = floor(x + 0.5);
+       else
+               x = ceil(x - 0.5);
+       if (ndigits < 0)
+               x *= f;
        else
-               return PyFloat_FromDouble(ceil(x*f - 0.5) / f);
+               x /= f;
+       return PyFloat_FromDouble(x);
 }
 
 static PyObject *