For a scientific application I need to output very precise numbers, so I have to print 15 significant figures. There are already questions on this topic here, but they all concern with truncating the digits, not printing more.
I realized that the print
function converts the input float
to a 10 character string
. Also, I became aware of the decimal
module, but that does not suit my needs.
So the question is, how can I easily print a variable amount of signifcant figures of my floats, where I need to display more than 10?
' + str(p) + 'e') % f) allows you to adjust the number of significant digits!
They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.
We round a number to three significant figures in the same way that we would round to three decimal places. We count from the first non-zero digit for three digits. We then round the last digit. We fill in any remaining places to the right of the decimal point with zeros.
Assuming you're only dealing with positive numbers, you can divide each number by the largest power of 10 smaller than the number, and then take the floor of the result.
Let:
>>> num = 0.0012345
For 3 significant figures:
>>> f'{num:.3}' '0.00123'
For 3 decimal places:
>>> f'{num:.3f}' '0.001'
See the "presentation types for floating point and decimal" table at the bottom of this section for any additional requirements provided by e, E, f, F, g, G, n, %, None
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With