I am trying to convert string into integar, like this:
money = "$163,852.06"
original_amount = money[1:]
print(int(original_amount))
Here I have to slice 'money' variable, so that I can get exact numbers only.
for which I am getting this error:
Traceback (most recent call last):
File "<string>", line 3, in <module>
ValueError: invalid literal for int() with base 10: '163,852.06'
Can someone help me on this?
CodePudding user response:
Your code has two issues:
Your number has a comma in it - Python does not interpret it as a valid part of a number.
You are applying an
int()
conversion to a string representing a number that is a float - it has a decimal part to it.
This solves both issues,
money = "$163,852.06"
original_amount = ('').join(money[1:].split(','))
print(int(float(original_amount)))
The code splits the number by the comma, then joins it immediately into a new whole - this will work with multiple commas as well.
Then it first converts the string to a float, and uses that float to obtain the final integer.