所以我有一個麻煩在python四捨五入浮動。我怎樣才能將錢浮起來?
這是我的輸出看起來像
Here is your receipt:
Coffe £ 1.2
HotChocolate £ 2.0
Latte £ 3.9000000000000004
Cappucino £ 2.2
Cake £ 1.5
Pensioner Yes
Takeout Yes
Total Cost: 11.664000000000001
我怎麼會值舍入到2 DP?
幫助將非常感激。
所以我有一個麻煩在python四捨五入浮動。我怎樣才能將錢浮起來?
這是我的輸出看起來像
Here is your receipt:
Coffe £ 1.2
HotChocolate £ 2.0
Latte £ 3.9000000000000004
Cappucino £ 2.2
Cake £ 1.5
Pensioner Yes
Takeout Yes
Total Cost: 11.664000000000001
我怎麼會值舍入到2 DP?
幫助將非常感激。
彩車有一個propertie,他們是不苛求,因爲機器的架構,Python有它不限過,嘗試像印刷:
print("%.2f" % some_float)
這個問題有你需要的一切:
樣品示例:
>>> x = 11.664000000000001
>>>
>>> round(x, 2)
11.66
>>>
>>> '{:0.2f}'.format(x)
'11.66'
>>>
>>> '%0.2f' % x
'11.66'
>>>
是的,是的,這是真的,很好的答案;) –
請仔細閱讀[後續回答](https://stackoverflow.com/questions/3410976/how-to-round-a-number-to-significant-figures-in-python)。 如果它只是在印刷中: print(「%。2f」%float) – IsaacDj
通常認爲'float'對於金額是不安全的。請參閱https://stackoverflow.com/questions/1406737/what-class-to-use-for-money-representation和https://stackoverflow.com/questions/7560455/decimals-to-2-places-for-money -in-python-3 – cdarke