This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: float function errors on negative number string with comma seperator ex: '-1,234.0'
Type: Stage: resolved
Components: Library (Lib) Versions: Python 3.9
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: jj.github.jj, steven.daprano
Priority: normal Keywords:

Created on 2021-12-26 16:10 by jj.github.jj, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg409202 - (view) Author: s s (jj.github.jj) Date: 2021-12-26 16:10
>>> float ('-1,234')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '-1,234'
msg409210 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2021-12-26 16:31
The behaviour is correct and not a bug. Commas are not supported when converting strings to float.

The allowed format for floats as strings is described in the docs:

https://docs.python.org/3/library/functions.html#float

By the way, the negative sign is irrelevant. Commas are not supported regardless of whether there is a negative sign or not.

The difficulty with commas is that it is ambiguous whether float('1,234') should interpret the comma as British/American digit grouping separator, and return 1234.0, or as the European decimal point, and return 1.234. For good or bad, Python has a bias towards English (like most programming languages) and so it chooses to only recognise the decimal point as a dot in the British/American style, and reject the comma.

If you want to support European-style commas as the decimal point, the easiest way is to call float('1,234'.replace(',', '.'))
msg409211 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2021-12-26 16:36
Aside: for what it is worth, the British style with a middle dot is also not supported: float('1·234') also raises ValueError.
History
Date User Action Args
2022-04-11 14:59:53adminsetgithub: 90341
2021-12-26 16:36:13steven.dapranosetmessages: + msg409211
2021-12-26 16:31:25steven.dapranosetstatus: open -> closed

nosy: + steven.daprano
messages: + msg409210

resolution: not a bug
stage: resolved
2021-12-26 16:10:13jj.github.jjcreate