[Tutor] Rounding to n significant digits

Alan Gauld alan.gauld at btinternet.com
Wed Sep 2 10:05:02 CEST 2009


"Richard Wagner" <wagnerr at umich.edu> wrote
> I'm fairly new to Python and am trying to find a simple way to round 
> floats to a specific number of significant digits.  I found an old  post 
> on this list with exactly the same problem:

The usual question is why would you want to lose precision in your data?
Significant digits is usually only an issue for presentation not internal 
storage.
That's why there is no built in way of losing precision (rounding) in the 
data.

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)))))

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list