Python floating-point precision format specifier

后端 未结 2 1297
一生所求
一生所求 2021-02-06 03:46

Let\'s say I have some 32-bit numbers and some 64-bit numbers:

>>> import numpy as np
>>> w = np.float32(2.4)
>>> x = np.float32(4.555         


        
2条回答
  •  离开以前
    2021-02-06 04:00

    I am not exactly sure what you are trying to accomplish. However, this might help. You wrote

    This seems to work reasonably well, but the precision number is also used up for numbers in front of the decimal place too, e.g. 34567.375768.

    You can use %f instead of g. From the Python docs:

    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'.

    >>> z = np.float64(4.555555555555555)
    >>> "%.3f" % z
    '4.556'
    >>> q = np.float64(2131234.555555555555555)
    >>> "%.3f" % q
    '2131234.556'
    >>>
    

提交回复
热议问题