How can I convert a string with dot and comma into a float in Python
Just remove the ,
with replace()
:
float("123,456.908".replace(',',''))
Convert Python strings into floats explicitly using the comma or the point as separators
because I don't know the locale settings
You could look that up using the locale
module:
>>> locale.nl_langinfo(locale.RADIXCHAR)
'.'
or
>>> locale.localeconv()['decimal_point']
'.'
Using that, your code could become:
import locale
_locale_radix = locale.localeconv()['decimal_point']
def read_float_with_comma(num):
if _locale_radix != '.':
num = num.replace(_locale_radix, ".")
return float(num)
Better still, the same module has a conversion function for you, called atof()
:
import locale
def read_float_with_comma(num):
return locale.atof(num)
Convert number strings with commas in pandas DataFrame to float
If you're reading in from csv then you can use the thousands arg:
df.read_csv('foo.tsv', sep='\t', thousands=',')
This method is likely to be more efficient than performing the operation as a separate step.
You need to set the locale first:
In [ 9]: import locale
In [10]: from locale import atof
In [11]: locale.setlocale(locale.LC_NUMERIC, '')
Out[11]: 'en_GB.UTF-8'
In [12]: df.applymap(atof)
Out[12]:
0 1
0 1200 4200.00
1 7000 -0.03
2 5 0.00
How to format a float with a comma as decimal separator in an f-string?
If you want to format floats with a comma within the f-string, you can either use replace after casting the float to a string:
position = 123.456
f"Position\t{str(position).replace('.',',')}"
A second option is to use the Python standard library module locale (but it is not thread-safe):
import locale
locale.setlocale(locale.LC_ALL, 'nl_NL')
f"Position\t{locale.format('%.3f', position)}"
A third option is to use the library babel (preferred in case of library routines):
from babel.numbers import format_decimal
f"Position\t{format_decimal(position, locale='nl_NL')}"
All three options return the same result for the given example:
'Position\t123,456'
replace dot and comma with each other from a number str in python
You might want to rely on switching the locale of the number, should such an API exist within Python. If you must do the substitution manually, then use re.sub
with lambda callback:
amt = '1.233.456.778,00'
output = re.sub(r'[.,]', lambda x: '.' if x.group() == ',' else ',', amt)
print(output) # 1,233,456,778.00
Note that this approach gets around the problem with your current approach, namely that if the string happens to have an @
in it, then your logic would fail.
Related Topics
What Are "Named Tuples" in Python
Pg_Config Executable Not Found
Having Django Serve Downloadable Files
Setting Y-Axis Limit in Matplotlib
How Does Zip(*[Iter(S)]*N) Work in Python
Proper Name for Python * Operator
I Can't Install Pyaudio on Windows? How to Solve "Error: Microsoft Visual C++ 14.0 Is Required."
How to Set Time Limit on Raw_Input
How to Groupby Consecutive Values in Pandas Dataframe
Error: Pandas Hashtable Keyerror
Understanding Dict.Copy() - Shallow or Deep
Beyond Top Level Package Error in Relative Import
Filter Dict to Contain Only Certain Keys
Python Error "Importerror: No Module Named"
Determine Whether Integer Is Between Two Other Integers