【Python】カンマ入りの文字列(string)を数値(float)に変換する【ValueError: could not convert string to float】

float('123,456.789')を実行したら、ValueError: could not convert string to floatが発生したときの解決法。




状況

>>> value_str ='123,456.789'
>>> float(value_str)

を実行したら、以下のようなエラーが発生。

ValueError: could not convert string to float: '123,456.789'

解決法

型変換する前に、replace()でカンマを削除する。

>>> float(value_str.replace(',', ''))
123456.789

参照

How can I convert a string with dot and comma into a float in Python
How can I convert a string like 123,456.908 to float 123456.908 in Python? For ints, see How to convert a string to a number if it has commas in it as thousands...

コメント