Displaying the output of a variable to more than 2 decimal places

后端 未结 4 1516
半阙折子戏
半阙折子戏 2020-12-20 02:14

I\'m trying to display the output of my addition to more than 2 decimal places.

import time
import random

max_number = 1000000.0
random_time = random.randra         


        
相关标签:
4条回答
  • 2020-12-20 02:34

    You'll find that if you hard-code the number of digits to print, you'll sometimes get too few or worse yet go past the floating-point precision and get meaningless digits at the end. The standard floating point number only has precision to about 15 digits. You can find out how many of those digits are to the right of the decimal point with this simple formula:

    digits_right = 14 - int(math.log10(value))
    

    Using that you can create an appropriate %f format:

    fmt = '%%0.%df' % max(0, digits_right)
    
    0 讨论(0)
  • 2020-12-20 02:48
    >>> f = 1/7.
    >>> repr(f)
    '0.14285714285714285'
    >>> str(f)
    '0.142857142857'
    >>> f
    0.14285714285714285
    >>> print f
    0.142857142857
    >>> '%.15f' % f
    '0.142857142857143'
    
    0 讨论(0)
  • 2020-12-20 02:52

    You already have the full number. Use a custom format specifier on output.

    >>> print '%.15f' % range_key
    1347053222.790798902511597
    
    0 讨论(0)
  • 2020-12-20 02:54

    When turning a float into a string (printing does this automatically), python limits it to only the 12 most significant digits, plus the decimal point.

    When returning the number from a function, you always get the full precision.

    To print more digits (if available), use string formatting:

    print '%f' % range_key  # prints 1347053958.526874
    

    That defaults to 6 digits, but you can specify more precision:

    print '%.10f' % range_key  # prints 1347053958.5268740654
    

    Alternatively, python offers a newer string formatting method too:

    print '{0:.10f}'.format(range_key)  # prints 1347053958.5268740654
    
    0 讨论(0)
提交回复
热议问题