Question

I want to do a print output in Python which gives everytime 2 digits. The problem is, that there are very large (or small) numbers so normal Python output gives like this:

5.89630388655e-09
8.93552349994e+14

but sometimes also normal numbers like:

345.8976

I just want to force it to have two digits, which means that the output for the large and small numbers are

5.89e-09
8.93e+14

and the normal numbers just capped (or rounded) at the second digits:

345.89 (or 345.90)

How is that possible to realize in Python?

Was it helpful?

Solution

In python you can format numbers in a way similar to other languages:

print '%.2f' % number
print '%.3g' % number

See string formatting for more details on available flags and conversions.

Alternatively, you can use str.format() or a Formatter:

'{0:.2f}'.format(number)
'{0:.3g}'.format(number)

See format string syntax for details on the format expression syntax.

The f conversion produces notation which always contains the decimal point and may result in very long string representation for large numbers and 0.00 for very small numbers.

The g conversion produces notation with or without the exponent depending on the size of the number. However, the precision argument is interpreted differently for g than for f conversion. For f it is the number of digits after the decimal point while for g it is the number of all significant digits displayed. See string formatting for details.

The reason for the different interpretation of the precision argument is that when dealing with numbers of very different magnitudes it makes a lot more sense to stick to a fixed number of significant digits.

If you decide to not follow convention here, you'll need to write code which uses different formatting expressions for numbers of different magnitude. Note however that this will result in your code producing numbers with different accuracy depending on their magnitude, e.g. 345.89 has five significant digits while 3.46e+10 and 3.46e-10 only three.

OTHER TIPS

You could use the format command:

"({0:.2f})".format(yournumber)

'.2f' means two decimal places

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top