Home > Mobile >  How can i fix this problem "could not convert string to float
How can i fix this problem "could not convert string to float

Time:09-23

I need to accept inputs in the form of 123.456,78.

num = float(input("enter your annual salary."))
thousands_separator = "."
fractional_separator = ","
num2 ="{:,.2f}".format(num)
print(num2)

hi

50.000,00

Traceback (most recent call last):

File "main.py", line 1, in

ValueError: could not convert string to float: '50.000,00'

CodePudding user response:

You cannot convert to float with a comma in the string. It only accepts a digit or a decimal point. So convert to a float after you edited it to the way python wants it.

This should help:

num = input("enter your annual salary.")
num = num.replace(".", "")
num = num.replace(",", ".")
thousands_separator = "."
fractional_separator = ","
num2 ="{:,.2f}".format(float(num))
print(num2)

CodePudding user response:

Easier way to do this.

salary = float(input("enter your annual salary."))
your_salary = f"${salary:,.2f}" 
print(your_salary)

output:

enter your annual salary.123456.78
$123,456.78
  • Related