Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string to integer with decimal in Python

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.

like image 365
Matt Hampel Avatar asked Jul 07 '09 20:07

Matt Hampel


People also ask

How do you convert string to decimal in Python?

If you are converting price (in string) to decimal price then.... from decimal import Decimal price = "14000,45" price_in_decimal = Decimal(price. replace(',','. '))

How do you convert a decimal to an integer in Python?

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.

How do you change string to decimal?

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.


1 Answers

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.

like image 182
Paolo Bergantino Avatar answered Sep 19 '22 06:09

Paolo Bergantino