Afaf
Afaf

Reputation: 654

Django conversion of unicode value to float doesn't work

This is the part of my code where I need to convert a Unicode value to float using float(), but I got the exception invalid literal float()

print("before conversion ",request.POST['prix'])
prix=request.POST['prix']
prixConvert= float(prix)
print("after conversion ")
print(prixConvert)

Upvotes: 1

Views: 281

Answers (1)

C14L
C14L

Reputation: 12558

As per your comment under the question, your "number" actually contains a ,. That is not a valid character for a float() call. You need to convert that into a . first.

print("before: {}".format(request.POST['prix']))

prix = request.POST['prix'].replace(',', '.')
prixConvert = float(prix)

print("after conversion: {}".format(prixConvert))

And better, catch the error and tell the user to supply a valid string

try:
    prixConvert = float(prix)
except ValueError:
    print('That was not a valid float number.')

If your input is very unreliable, you can add more .replace() calls to "clean up" the input before converting, that way you may catch more numbers that are hidden within otherwise invalid input.

Upvotes: 1

Related Questions