本文介紹了格式化沒有尾隨零的浮點數的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
如何格式化浮點數以使其不包含尾隨零?換句話說,我希望生成的字符串盡可能短.
How can I format a float so that it doesn't contain trailing zeros? In other words, I want the resulting string to be as short as possible.
例如:
3 -> "3"
3. -> "3"
3.0 -> "3"
3.1 -> "3.1"
3.14 -> "3.14"
3.140 -> "3.14"
推薦答案
我,我會做 ('%f' % x).rstrip('0').rstrip('.')
-- 保證定點格式而不是科學記數法等.是的,不像 %g
那樣流暢和優雅,但是,它可以工作(我不知道如何強制 %g
永遠不要使用科學記數法;-).
Me, I'd do ('%f' % x).rstrip('0').rstrip('.')
-- guarantees fixed-point formatting rather than scientific notation, etc etc. Yeah, not as slick and elegant as %g
, but, it works (and I don't know how to force %g
to never use scientific notation;-).
這篇關于格式化沒有尾隨零的浮點數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!