Ethan Keller
Ethan Keller

Reputation: 1053

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.

Upvotes: 3

Views: 1172

Answers (2)

GPhilo
GPhilo

Reputation: 19123

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)

Upvotes: 4

Salva.
Salva.

Reputation: 139

Have a look at:

https://pyformat.info/

""" Python has had awesome string formatters for many years but the documentation on them is far too theoretic and technical. With this site we try to show you the most common use-cases covered by the old and new style string formatting API with practical examples.

All examples on this page work out of the box with with Python 2.7, 3.2, 3.3, 3.4, and 3.5 without requiring any additional libraries.

Further details about these two formatting methods can be found in the official Python documentation: """

Upvotes: 0

Related Questions