Fixed digits after decimal with f-strings

前端 未结 5 926
故里飘歌
故里飘歌 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:46

    a = 10.1234
    
    print(f"{a:0.2f}")
    

    in 0.2f:

    • 0 is telling python to put no limit on the total number of digits to display
    • .2 is saying that we want to take only 2 digits after decimal (the result will be same as a round() function)
    • f is telling that it's a float number. If you forget f then it will just print 1 less digit after the decimal. In this case, it will be only 1 digit after the decimal.

    A detailed video on f-string for numbers https://youtu.be/RtKUsUTY6to?t=606

提交回复
热议问题