python - 从浮点数中删除所有小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22623375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:18:08  来源:igfitidea点击:

python - remove all decimals from a float

python

提问by user3196332

How can I remove all decimal places form a float?

如何从浮点数中删除所有小数位?

a = 100.0

a = 100.0

I want that to become 100

我希望它变成 100

I tried str(a).rstrip('.0'), but it just returned 1

我试过了str(a).rstrip('.0'),但它刚回来1

采纳答案by Paulo Bu

What about converting it to int?

把它转换成int什么?

>>>int(a)
100

Just for the sake of completeness, there are many many ways to remove the decimal part from a string representation of a decimal number, one that I can come up right now is:

为了完整起见,有很多方法可以从十进制数的字符串表示中删除小数部分,我现在可以想到的方法是:

s='100.0'
s=s[:s.index('.')]
s
>>>'100'

Perhaps there's another one more simple.

也许还有一个更简单的。

Hope this helps!

希望这可以帮助!

回答by ederollora

If you do not want to convert it to an int you can also split it.

如果您不想将其转换为 int,您也可以拆分它。

>>> a = 100.25
>>> str(a).split('.')[0]
>>> '100'  # result is now a string

回答by Colton Allen

If you're deriving the float you can floor it with //

如果您正在推导浮点数,您可以使用 //

a = 200 / 2 # outputs 100.0
a = 200 // 2 # outputs 100

Faster than typecasting afterwards!

比之后的类型转换更快!

回答by Prateek Gupta

In simple words,int()method in python is the type conversion function similar to float()and str(), and can be used for converting float numbers to int numbers.

简单来说,int()python中的method就是类似于float()and的类型转换函数str(),可以用来将float数转换为int数。