天天看點

格式化浮點數

from math import pi
format = 'pi with three decimals:  .%3f'
print (format % pi)
pi with three decimals: 
           

今天學習的時候因為輸錯了,導緻出現了自己無法了解的結果。為什麼是.3.141593呢?

format = 'pi with three decimals:  % 3.f'
print (format % pi)
pi with three decimals:   
           

這是另一個錯誤。

format = 'pi with three decimals: % .3f'
print (format % pi)
pi with three decimals: 
           

這是書中正确的例句。

'%.3f' % pi 
'3.142'
           

取pi的三位小數