How to convert a negative number stored as string to a float?
Am getting this error on Python 3.6 and don't know how to get over it.
>>> s = '–1123.04'
>>> float(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '–1123.04'
Float Data Type in Python Float represents floating point numbers in python. Decimal numbers or you can say real numbers are represented in python using double precision floating point numbers. A floating point number can be positive, negative or zero.
The Python "ValueError: could not convert string to float" occurs when we pass a string that cannot be converted to a float (e.g. an empty string or one containing characters) to the float() class. To solve the error, remove all unnecessary characters from the string.
In Python, positive numbers can be changed to negative numbers with the help of the in-built method provided in the Python library called abs (). When abs () is used, it converts negative numbers to positive. However, when -abs () is used, then a positive number can be changed to a negative number.
We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number.
Your string contains a unicode en-dash, not an ASCII hyphen. You could replace it:
>>> float('–1123.04'.replace('\U00002013', '-'))
-1123.04
For a more generic solution, you can use regular expressions (regex) to replace all non-ascii characters with a hyphen.
import re
s = '–1123.04'
s = re.sub(r'[^\x00-\x7F]+','-', s)
s = float(s)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With