Python 百分比計算


遇到計算百分比的情況,查了一下,有兩種方式

 

具體實現方式見下面代碼

 

   # 方式1  格式化為float ,然后 處理成%格式, 需要對分子/分母 * 100如下,
        percentList.append('{:.2f}%'.format(member/denominator*100))
        # 方式2 直接使用參數格式化:{:.2%}  {:.2%}: 顯示小數點后2位
        percentList.append('{:.2%}'.format(member/denominator))
    print("所求百分比為:",percentList)


# 說明
# { } 的意思是對應format()的一個參數,按默認順序對應,參數序號從0開始,{0}對應format()的第一個參數,{1}對應第二個參數。例如:

# 默認順序:
print('percent1: {:.2%}, percent2: {:.1%}'.format(42/50, 42/100))
# percent1: 84.00%, percent2: 42.0%

# 指定順序:
# {1:.1%}對應第2個參數; {0:.1%}對應第1個參數。
print('percent2: {1:.1%}, percent1: {0:.1%}'.format(42/50, 42/100))
# percent2: 42.0%, percent1: 84.0%

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM