2009/9/2 Alan Gauld <[email protected]>:
> That having been said the two approaches, string or math, are equally
> valid. I suspect the math version will be much slower since it calls
> several functions but I haven't timed it.
>
>>> def round_to_n(x, n):
>>> fmt = "%%.%de" % (n)
>>> return float( fmt % x)
>>
>>> import math
>>>
>>> def round_figures(x, n):
>>> return round(x, int(n - math.ceil(math.log10(abs(x)))))
Maybe the decimal module can help out. It can limit precision to n
digits globally and per instance. I might be way of here so please do
not hesitate to correct me :-)
>>> i = float(1.333333)
>>> i
1.3333330000000001
>>> c = decimal.getcontext().copy()
>>> c.prec = 2
>>> d = c.create_decimal(str(i))
>>> d
Decimal('1.3')
>>> x = 2
>>> x < d
False
>>> x > d
True
Greets
Sander
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor