Change default float print format

28,568

Solution 1

You are not allowed to monkeypatch C types, like Ignacio said.

However, if you are terribly pressed in doing so and you know some C, you could go modify the Python interpreter source code yourself, then recompile it into a custom solution. Once I modified one of the standard behaviors for lists and it was only a moderate pain.

I suggest you find a better solution, such as just printing the floats with the "%0.2f" printf notation:

for item in mylist:
    print '%0.2f' % item,

or

print " ".join('%0.2f' % item for item in mylist)

Solution 2

>>> a = 0.1
>>> a
0.10000000000000001
>>> print a
0.1
>>> print "%0.3f" % a
0.100
>>>

From the Python docs, repr(a) would give 17 digits (as seen by just typing a at the interactive prompt, but str(a) (automatically performed when you print it) rounds to 12.

Edit: Most basic hack solution... You have to use your own class though, so...yeah.

>>> class myfloat(float):
...     def __str__(self):
...             return "%0.3f" % self.real
>>> b = myfloat(0.1)
>>> print repr(b)
0.10000000000000001
>>> print b
0.100
>>>

Solution 3

This doesn't answer the more general question of floats nested in other structures, but if you just need to print floats in lists or even array-like nested lists, consider using numpy.

e.g.,

import numpy as np
np.set_printoptions(precision=3, suppress=False)
list_ = [[1.5398, 2.456, 3.0], 
         [-8.397, 2.69, -2.0]]
print(np.array(list_))

gives

[[ 1.54   2.456  3.   ]
 [-8.397  2.69  -2.   ]]

Solution 4

I ran into this issue today, and I came up with a different solution. If you're worried about what it looks like when printed, you can replace the stdout file object with a custom one that, when write() is called, searches for any things that look like floats, and replaces them with your own format for them.

class ProcessedFile(object):

    def __init__(self, parent, func):
        """Wraps 'parent', which should be a file-like object,
        so that calls to our write transforms the passed-in
        string with func, and then writes it with the parent."""
        self.parent = parent
        self.func = func

    def write(self, str):
        """Applies self.func to the passed in string and calls
        the parent to write the result."""
        return self.parent.write(self.func(str))

    def writelines(self, text):
        """Just calls the write() method multiple times."""
        for s in sequence_of_strings:
            self.write(s)

    def __getattr__(self, key):
        """Default to the parent for any other methods."""
        return getattr(self.parent, key)

if __name__ == "__main__":
    import re
    import sys

    #Define a function that recognises float-like strings, converts them
    #to floats, and then replaces them with 1.2e formatted strings.
    pattern = re.compile(r"\b\d+\.\d*\b")
    def reformat_float(input):
        return re.subn(pattern, lambda match: ("{:1.2e}".format(float(match.group()))), input)[0]

    #Use this function with the above class to transform sys.stdout.
    #You could write a context manager for this.
    sys.stdout = ProcessedFile(sys.stdout, reformat_float)
    print -1.23456
    # -1.23e+00
    print [1.23456] * 6
    # [1.23e+00, 1.23e+00, 1.23e+00, 1.23e+00, 1.23e+00, 1.23e+00]
    print "The speed of light is  299792458.0 m/s."
    # The speed of light is  3.00e+08 m/s.
    sys.stdout = sys.stdout.parent
    print "Back to our normal formatting: 1.23456"
    # Back to our normal formatting: 1.23456

It's no good if you're just putting numbers into a string, but eventually you'll probably want to write that string to some sort of file somewhere, and you may be able to wrap that file with the above object. Obviously there's a bit of a performance overhead.

Fair warning: I haven't tested this in Python 3, I have no idea if it would work.

Solution 5

No, because that would require modifying float.__str__(), but you aren't allowed to monkeypatch C types. Use string interpolation or formatting instead.

Share:
28,568
AkiRoss
Author by

AkiRoss

Computer Scientist. I am gonna build the first intelligent program. And I'll order it to increase my StackOverflow reputation.

Updated on May 27, 2020

Comments

  • AkiRoss
    AkiRoss almost 4 years

    I've some lists and more complex structures containing floats. When printing them, I see the floats with a lot of decimal digits, but when printing, I don't need all of them. So I would like to define a custom format (e.g. 2 or 3 decimals) when floats are printed.

    I need to use floats and not Decimal. Also, I'm not allowed to truncate/round floats.

    Is there a way to change the default behavior?

  • AkiRoss
    AkiRoss almost 14 years
    The problem is that I've float inside lists, and when I print(list) I've no control on that. (This applies also for other objects, btw). Modifying source code is feasible as I know C, but isn't exactly what I was thinking of. Thanks.
  • Donald Miner
    Donald Miner almost 14 years
    @AkiRoss, if you want more control just print the items individually.
  • AkiRoss
    AkiRoss almost 14 years
    @Ignacio, and what can I do if I've objects that use float.__str__ or float.__repr__ to str or repr themselves? What if I've nested lists with arbitrary length? I think that fixing these would be just wrong. Python provides str and repr, and I think that the Right Way is to change them. I didn't know they were fixed for C types.
  • AkiRoss
    AkiRoss almost 14 years
    Also, using a custom wrapper as Nick T suggested, would require to wrap all the computations, and I can't.
  • AkiRoss
    AkiRoss almost 14 years
    If print uses str(obj) to convert the object to string, can't I override the default str() to return a custom string in case the parameter is a float and return the normal str() for the rest? I was reading PEP 3140
  • dan04
    dan04 almost 14 years
    Actually, it would require modifying float.__repr__. str only uses 12 significant digits.
  • AkiRoss
    AkiRoss almost 14 years
    Already using it. That's not the point, but thanks for the tip.
  • Bruce
    Bruce almost 13 years
    He's explicitely using python tags, thus he's not using C
  • obchardon
    obchardon about 6 years
    In python 3 you will use print('{0:.2f}'.format(item))