Nicely representing a floating-point number in python

Posted by dln385 on Stack Overflow See other posts from Stack Overflow or by dln385
Published on 2010-04-18T19:29:00Z Indexed on 2010/04/18 19:33 UTC
Read the original article Hit count: 354

I want to represent a floating-point number as a string rounded to some number of significant digits, and never using the exponential format. Essentially, I want to display any floating-point number and make sure it “looks nice”.

There are several parts to this problem:

  • I need to be able to specify the number of significant digits.
  • The number of significant digits needs to be variable, which can't be done with with the string formatting operator.
  • I need it to be rounded the way a person would expect, not something like 1.999999999999

I've figured out one way of doing this, though it looks like a work-round and it's not quite perfect. (The maximum precision is 15 significant digits.)

>>> def f(number, sigfig):
    return ("%.15f" % (round(number, int(-1 * floor(log10(number)) + (sigfig - 1))))).rstrip("0").rstrip(".")

>>> print f(0.1, 1)
0.1
>>> print f(0.0000000000368568, 2)
0.000000000037
>>> print f(756867, 3)
757000

Is there a better way to do this? Why doesn't Python have a built-in function for this?

© Stack Overflow or respective owner

Related posts about python

Related posts about floating-point