2012-06-10 24 views
2

像以下類似的帖子不回答我的問題。 Convert a string to integer with decimal in Python如何在Python中將字符串轉換爲十進制數字進行算術運算?

考慮以下Python代碼。

>>> import decimal 
>>> s = '23.456' 
>>> d = decimal.Decimal(s) 
>>> d 
Decimal('23.456')   # How do I represent this as simply 23.456? 
>>> d - 1 
22       # How do I obtain the output to be 22.456? 

如何將字符串轉換爲十進制數,以便我能夠對其執行算術運算並獲得正確精度的輸出?

+0

看起來像上一個問題。使用float()。 http://stackoverflow.com/questions/482410/how-do-i-convert-a-string-to-a-double-in-python –

+0

這有什麼錯'X =浮動(23.456) - 1'。 – RanRag

+0

http:// ideone。com/TA3js – wroniasty

回答

2

如果你想留在decimal數字,最安全的是一切轉換:

>>> s = '23.456' 
>>> d = decimal.Decimal(s) 

>>> d - decimal.Decimal('1') 
Decimal('22.456') 
>>> d - decimal.Decimal('1.0') 
Decimal('22.456') 

在Python 2.7,有一個爲整數的隱式轉換,而不是浮動。

>>> d - 1 
Decimal('22.456') 
>>> d - 1.0 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: unsupported operand type(s) for -: 'Decimal' and 'float' 
0

使用bultin浮動功能:

>>> d = float('23.456') 
>>> d 
23.456 
>>> d - 1 
22.456 

在這裏看到的文檔:http://docs.python.org/library/functions.html#float

+0

確切地說:http://ideone.com/TA3js – wroniasty

+0

我認爲浮動不是那麼精確。如果這個數字需要更高的精度,這是否是一個有效的解決方案? – idealistikz

+0

在Python中,一個float等價於一個c double。你需要多少精度? – Trevor

0

是您的計算需要的DecimalDecimal fixed point and floating point arithmetic文件概述了它們的區別。如果沒有,你可能只是做

d = float('23.456') 
d 
23.456 

d - 1 
22.456 

奇怪的是重新Decimal,我得到這個交互

d = decimal.Decimal('23.456') 

d 
Decimal('23.456') 
d - 1 
Decimal('22.456') 

但是,當我打印出來,我得到的值

print d 
23.456 
print d-1 
22.456 
+1

浮動是不一樣的東西:浮置(「100000000.0」)+浮動(「0.000000001」)爲100000000.0 – wroniasty

+0

@wroniasty我沒有聲稱是,我只是問是否需要。兩者之間的差異在這裏很清楚地概括:http://docs.python.org/library/decimal.html – Levon

+0

@wroniasty:如果OP使用小數到千分之一的地方,我真的不會看到它很大程度上有所不同。 –

0

我的Python似乎以不同的方式做:

>>> s = '23.456' 
>>> d = decimal.Decimal(s) 
>>> d 
Decimal('23.456') 
>>> d-1 
Decimal('22.456') 

你使用的是什麼版本/操作系統?

+0

我使用Python 2.7在Windows 7上。 – idealistikz

0

您是否正在專門嘗試使用Decimal任意精度庫,或者您只是在努力將字符串轉換爲Python float?

如果你想十進制使用:

>>> import decimal 
>>> s1='23.456' 
>>> s2='1.0' 
>>> decimal.Decimal(s1) - decimal.Decimal(s2) 
Decimal('22.456') 
>>> s1='23.456' 
>>> s2='1' 
>>> decimal.Decimal(s1) - decimal.Decimal(s2) 
Decimal('22.456') 

或者說,我認爲是更可能的是,你正試圖只是字符串轉換爲一個Python浮點值:

>>> s1='23.456' 
>>> s2='1' 
>>> float(s1)-float(s2) 
22.456 
>>> float(s1)-1 
22.456 
>>> float(s1)-1.0 
22.456 
0

如果使用浮點數,當數字變得太大 - x = 29345678.91例如 - 您會得到您可能不期望的結果。在這種情況下,float(x)變爲2.934567891E7這似乎是不受歡迎的,尤其是如果使用財務數字。

相關問題