1

I'm looking for a string conversion function/module in Python that is based upon significant digits (figures). The usefulness for this functionality has come up several times, so it seems hard to believe that Python still doesn't have a function or module to do this easily. Does anyone know if anything new has come out? If not, would this be a good opportunity for a feature request?

Disclaimers:

  1. I realize that this is a topic that has several questions already, but most of them are several years old. I'm hoping something has been released recently, as useful as it seems.
  2. I also realize that it is relatively simple to write a function to do this manually, but I would prefer a module or (better) a built-in function for portability.
  3. I'm not looking for the output to be in exponential notation

Functionality examples:

>>> from somemodule import SDStr

>>> SDStr(num=1234, sigDigs=3)
'1230'

>>> SDStr(num=12.3456, sigDigs=4)
'12.35'

>>> SDStr(num=100, sigDigs=3)
'100.'

>>> SDStr(num=100.0, sigDigs=2)
'100'

>>> SDStr(num=100, sigDigs=4)
'100.0'

>>> SDStr(num=0.001234, sigDigs=2)
'0.0012'
Bryant
  • 664
  • 2
  • 9
  • 23
  • See http://stackoverflow.com/a/18886013/5987 for the start of an answer. There's code to round to a fixed 15 decimal places but it could be adapted. – Mark Ransom Sep 27 '13 at 19:24

1 Answers1

0
import decimal

def rounded(number, figures):
    number = decimal.Decimal(number)
    return format(round(number, -number.adjusted()-1+figures), "f")

decimal keeps track of decimal digits, so obviously this is the way to do things.

I just adjust the number of significant figures by the place of the most significant digit and format it to a float. It works like a charm.

EDIT: For some reason Python 2's not liking this. I'll look into it.

Well, basically in Python 2 round coerces to a float (seriously, move to Python 3), so the simple answer is:

from decimal import Decimal

def rounded(number, figures):
    number = Decimal(number)
    decimal_shift = -number.adjusted()-1+figures
    integral = round(number * Decimal(10) ** decimal_shift)
    rounded_decimal = Decimal(integral) * Decimal(10) ** -decimal_shift
    return format(rounded_decimal, "f")
Veedrac
  • 58,273
  • 15
  • 112
  • 169