Fixed digits after decimal with f-strings

前端 未结 5 936
故里飘歌
故里飘歌 2020-11-28 01:15

Is there an easy way with Python f-strings to fix the number of digits after the decimal point? (Specifically f-strings, not other string formatting options like .format or

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 01:43

    Adding to Rob's answer, you can use format specifiers with f strings (more here).

    • You can control the number of decimals:
    pi = 3.141592653589793238462643383279
    
    print(f'The first 6 decimals of pi are {pi:.6f}.')
    
    The first 6 decimals of pi are 3.141593.
    
    • You can convert to percentage:
    grade = 29/45
    
    print(f'My grade rounded to 3 decimals is {grade:.3%}.')
    
    My grade rounded to 3 decimals is 64.444%.
    
    • You can do other things like print constant length:
    from random import randint
    for i in range(5):
        print(f'My money is {randint(0, 150):>3}$')
    
    My money is 126$
    My money is   7$
    My money is 136$
    My money is  15$
    My money is  88$
    
    • Or even print with a comma thousand separator:
    print(f'I am worth {10000000000:,}$')
    
    I am worth 10,000,000,000$
    

提交回复
热议问题