Convert a string to integer with decimal in Python
Solution 1
How about this?
>>> s = '23.45678'
>>> int(float(s))
23
Or...
>>> int(Decimal(s))
23
Or...
>>> int(s.split('.')[0])
23
I doubt it's going to get much simpler than that, I'm afraid. Just accept it and move on.
Solution 2
What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:
s = '234.67'
i = int(round(float(s)))
Otherwise, just do:
s = '234.67'
i = int(float(s))
Solution 3
>>> s = '23.45678'
>>> int(float(s))
23
>>> int(round(float(s)))
23
>>> s = '23.54678'
>>> int(float(s))
23
>>> int(round(float(s)))
24
You don't specify if you want rounding or not...
Solution 4
You could use:
s = '23.245678'
i = int(float(s))
Solution 5
"Convert" only makes sense when you change from one data type to another without loss of fidelity. The number represented by the string is a float and will lose precision upon being forced into an int.
You want to round instead, probably (I hope that the numbers don't represent currency because then rounding gets a whole lot more complicated).
round(float('23.45678'))
Matt Hampel
Updated on July 05, 2022Comments
-
Matt Hampel almost 2 years
I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.
Direct conversion fails:
>>> s = '23.45678' >>> i = int(s) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '23.45678'
I can convert it to a decimal by using:
>>> from decimal import * >>> d = Decimal(s) >>> print d 23.45678
I could also split on '.', then subtract the decimal from zero, then add that to the whole number ... yuck.
But I'd prefer to have it as an int, without unnecessary type conversions or maneuvering.
-
teewuane about 9 yearsRemember to
import decimal
then use it asdecimal.Decimal(5)
or dofrom decimal import Decimal
and use it asDecimal(5)
. I always forget. -
Rapnar over 8 yearsYou should note the type of rounding each option offers to the value.