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.
If you are converting price (in string) to decimal price then.... from decimal import Decimal price = "14000,45" price_in_decimal = Decimal(price. replace(',','. '))
In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.
Converting a string to a decimal value or decimal equivalent can be done using the Decimal. TryParse() method. It converts the string representation of a number to its decimal equivalent.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With