Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - remove all decimals from a float

Tags:

python

How can I remove all decimal places form a float?

a = 100.0

I want that to become 100

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

like image 500
user3196332 Avatar asked Mar 25 '14 00:03

user3196332


2 Answers

What about converting it to 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!

like image 156
Paulo Bu Avatar answered Sep 27 '22 21:09

Paulo Bu


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

>>> a = 100.25
>>> str(a).split('.')[0]
>>> '100'  # result is now a string
like image 27
ederollora Avatar answered Sep 27 '22 22:09

ederollora