How can I print many significant figures in Python?

后端 未结 6 1969
独厮守ぢ
独厮守ぢ 2020-12-16 12:53

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 c

6条回答
  •  情话喂你
    2020-12-16 13:11

    To display N significant figures (not decimal places) you use the "g" format:

    >>> x = 1.23
    >>> print("%.2g" % x)
    1.2
    >>> x = 12.3
    >>> print("%.2g" % x)
    12
    

    See format spec for details on precision:

    The precision is a decimal number indicating how many digits should be displayed after the decimal point for a floating point value formatted with 'f' and 'F', or before and after the decimal point for a floating point value formatted with 'g' or 'G'. For non-number types the field indicates the maximum field size - in other words, how many characters will be used from the field content. The precision is not allowed for integer values.

提交回复
热议问题