Tuesday, May 3, 2011

keeping same formatting for floating point values

I have a python program that reads floating point values using the following regular expression

 (-?\d+\.\d+)

once I extract the value using float(match.group(1)), I get the actual floating point number. However, I am not able to distinguish if the number was 1.2345678 or 1.234 or 1.2340000.

The problem I am facing is to print out the floating point value again, with the exact same formatting. An easy solution is to "split and count" the floating point value when still a string, eg splitting at the decimal point, and counting the integer part length and the fractional part length, then create the formatter as

print "%"+str(total_len)+"."+str(fractional_len)+"f" % value

but maybe you know a standard way to achieve the same result ?

From stackoverflow
  • If you want to keep a fixed precision, avoid using floats and use Decimal instead:

    >>> from decimal import Decimal
    >>> d = Decimal('-1.2345')
    >>> str(d)
    '-1.2345'
    >>> float(d)
    -1.2344999999999999
    
    Stefano Borini : Cool, I didn't know that!
    S.Lott : Better still, keep it as string as long as possible.
  • >>> from decimal import Decimal as d
    >>> d('1.13200000')
    Decimal('1.13200000')
    >>> print d('1.13200000')
    1.13200000
    
  • You method is basically correct. String formatting has a less often used * operator you can put for the formatting sizes, here's some code:

    import re
    
    def parse_float(str):
      re_float = re.compile(r'(-?)(\d+)\.(\d+)')
      grps = re_float.search(str)
      sign, decimal, fraction = grps.groups()
      float_val = float('%s%s.%s' % (sign, decimal, fraction))
      total_len = len(grps.group(0))
      print '%*.*f'  % (total_len, len(fraction), float_val)
    
    parse_float('1.2345678')
    parse_float('1.234')
    parse_float('1.2340000')
    

    and it outputs

    1.2345678
    1.234
    1.2340000
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.