Search code examples
pythonpint

pint significant figures, precision


I'm looking for a way to tell pint how many significant figures to print. For instance, when I type this:

import pint
ureg = pint.UnitRegistry()
print(3*ureg.m /9)
0.3333333333333333 meter

You can see that the printed representation has many significant digits. Is there a way to set the number of sig digits something like numpy.set_print_options() ... ? Or do I have to manually overwrite the Quantity print function?

One option pointed out in gphilo's answer below, I could set the ureg.default_format field in pint, but that doesn't work when trying to print arrays. See here for the error.


Solution

  • Supposing you want 3 significative figures:

    print('{:.3f}'.format(3*ureg.m /9))
    

    pint supports PEP 3101 string formatting syntax

    Accordint to the version's 0.8.1 documentation you can also set the default formatting via:

    ureg.default_format = '.3f'
    print(3*ureg.m /9)