![](/img/trans.png)
[英]How to remove the last space and following digit from a variable python
[英]How to remove last decimal digit from float in python?
假設我有一個任意浮點數x = 123.123456
並想從浮點數中刪除最后 n 個十進制數字,即n = 1
然后x = 123.12345
, n = 2
然后x = 123.1234
等等。 這如何在 python 中實現?
這將完成您所要求的技巧,但請注意浮點數的問題。
# let's cut 2 digits
n = 2
# naively we can do this
f = 123.123456
short_f = float(str(f)[:-n])
# but watch out for floating point error
f = 1.2 - 1.0 # f should be 0.2 but is actually 0.19999999999999996
short_f = float(str(f)[:-n]) # so this gives 0.199999999999999
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.