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

后端 未结 4 1554
半阙折子戏
半阙折子戏 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)
    

提交回复
热议问题