編輯 - 使用十進制專門 - 全例如
import decimal
def simplify(text):
# might be a : separated value
text = text.split(':')[-1]
# turn into decimal
number = decimal.Decimal(text)
# remove everything but the ones place and forwards
number = number - (number/10).quantize(1, rounding=decimal.ROUND_FLOOR) * 10
# truncate to the thousandths
return number.quantize(decimal.Decimal('.001'), rounding=decimal.ROUND_FLOOR)
a = '121082008.3399'
b = '21:53:28.339'
assert simplify(a) == simplify(b)
print simplify(a), '=', simplify(b)
斯科特如果你比較使用字符串,那麼你不需要任何花車的數量和將不會有「四捨五入」怎麼回事。
'8.339' == '8.339'
,或者,如果你有
a = '8.3399'
b = '8.339'
然後
a[:-1] == b
但是,如果你決定與他們「數字」的工作,那麼作爲伊格納西奧指出的那樣,你可以使用小數點。
from decimal import Decimal
number_a = Decimal(a[:-1])
number_b = Decimal(b)
現在
number_a == number_b
希望幫助
對我怎麼能夠無視數的第一部分的任何想法(從121082008.3399我只想8.339 - 基本上只是斬去號碼的第一個和最後一個部分。)同時使用十進制模塊?謝謝! – Scott 2011-04-24 21:26:25
@Scott:使用十進制模塊是極端的矯枉過正......只是把你的字符串切碎;看到我的答案。 – 2011-04-24 23:34:20