Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to convert a string with floats numbers to another data type?

the string will be the price of some product, so it will basically come like this ‘1,433.10’, the problem is that I need to compare it with the value that the user enters in an input that is only possible to enter integers because of the isdigit() method , used to check if the input is a number, and this causes the comparison to fail.
I already tried converting to int, to float and nothing worked, it only generated exceptions

def convert_values():
        price = results['price'][2:] # here is where the string with the value is, which in this case is '1,643.10'
        print(int(float(price))) # if I try to cast just to int: ValueError: invalid literal for int() with base 10: '1,643.10'

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Before converting, replace the commas in the string with '' as:

price = results['price'][2:].replace(',', '')
print(int(float(price)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading