問題描述
round() 函數的文檔說明您通過它是一個數字,小數點后的位置要四舍五入.因此它應該這樣做:
The documentation for the round() function states that you pass it a number, and the positions past the decimal to round. Thus it should do this:
n = 5.59
round(n, 1) # 5.6
但是,實際上,舊的浮點怪異現象逐漸出現,您會得到:
But, in actuality, good old floating point weirdness creeps in and you get:
5.5999999999999996
出于 UI 的目的,我需要顯示 5.6
.我在互聯網上一探究竟,發現了一些 文檔取決于我對 Python 的實現.不幸的是,這發生在我的 Windows 開發機器和我嘗試過的每臺 Linux 服務器上.另見此處.
For the purposes of UI, I need to display 5.6
. I poked around the Internet and found some documentation that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. See here also.
沒有創建自己的圓形庫,有什么辦法解決這個問題嗎?
Short of creating my own round library, is there any way around this?
推薦答案
我無法控制它的存儲方式,但至少格式可以正常工作:
I can't help the way it's stored, but at least formatting works correctly:
'%.1f' % round(n, 1) # Gives you '5.6'
這篇關于round() 似乎沒有正確舍入的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!