Pythonで123,456.908floatのような文字列を変換するにはどうすればよい123456.908ですか?
回答:
ただ、削除,してreplace():
float("123,456.908".replace(',',''))
python cd_size = float("737,280,000".replace(',','')) (私は実際にintを使用しました)
setlocaleそもそもそういうわけです。
...または、コンマをフィルターで除外するゴミとして扱う代わりに、文字列全体をfloatのローカライズされたフォーマットとして扱い、ローカリゼーションサービスを使用することもできます。
from locale import atof, setlocale, LC_NUMERIC
setlocale(LC_NUMERIC, '') # set to your default locale; for me this is
# 'English_Canada.1252'. Or you could explicitly specify a locale in which floats
# are formatted the way that you describe, if that's not how your locale works :)
atof('123,456') # 123456.0
# To demonstrate, let's explicitly try a locale in which the comma is a
# decimal point:
setlocale(LC_NUMERIC, 'French_Canada.1252')
atof('123,456') # 123.456
Extension modules should never call setlocale()
atof は文字列の組み込みメソッドです。ここで使用しているのは、標準ライブラリモジュールの関数atofであり、locale非推奨ではありません。
locale.atof
ロケールがわからず、任意の種類の数値を解析する場合は、このparseNumber(text)関数を使用してください。それは完璧ではありませんが、ほとんどの場合を考慮に入れてください:
>>> parseNumber("a 125,00 €")
125
>>> parseNumber("100.000,000")
100000
>>> parseNumber("100 000,000")
100000
>>> parseNumber("100,000,000")
100000000
>>> parseNumber("100 000 000")
100000000
>>> parseNumber("100.001 001")
100.001
>>> parseNumber("$.3")
0.3
>>> parseNumber(".003")
0.003
>>> parseNumber(".003 55")
0.003
>>> parseNumber("3 005")
3005
>>> parseNumber("1.190,00 €")
1190
>>> parseNumber("1190,00 €")
1190
>>> parseNumber("1,190.00 €")
1190
>>> parseNumber("$1190.00")
1190
>>> parseNumber("$1 190.99")
1190.99
>>> parseNumber("1 000 000.3")
1000000.3
>>> parseNumber("1 0002,1.2")
10002.1
>>> parseNumber("")
>>> parseNumber(None)
>>> parseNumber(1)
1
>>> parseNumber(1.1)
1.1
>>> parseNumber("rrr1,.2o")
1
>>> parseNumber("rrr ,.o")
>>> parseNumber("rrr1rrr")
1
小数の区切り文字としてコンマがあり、千の区切り文字としてドットがある場合は、次のことができます。
s = s.replace('.','').replace(',','.')
number = float(s)
それが役立つことを願っています
これが私があなたのために書いた簡単な方法です。:)
>>> number = '123,456,789.908'.replace(',', '') # '123456789.908'
>>> float(number)
123456789.908
reそのようなタスクのための大きなハンマーです。
float(number)はその説明的なタッチのために好きです。+1 ;-)
,replace()に置き換えるだけです。
f = float("123,456.908".replace(',',''))
print(type(f)
type()は、floatに変換されたことを示します
さまざまな通貨フォーマットのためのより良いソリューション:
def text_currency_to_float(text):
t = text
dot_pos = t.rfind('.')
comma_pos = t.rfind(',')
if comma_pos > dot_pos:
t = t.replace(".", "")
t = t.replace(",", ".")
else:
t = t.replace(",", "")
return(float(t))
localeモジュールを使用することです。他のすべては、将来トラブルに巻き込まれる非常に厄介なハックです。