問題描述
我一直在編寫一個(gè)腳本,該腳本從 Excel 電子表格中獲取數(shù)據(jù),對數(shù)字進(jìn)行四舍五入并刪除小數(shù)點(diǎn),例如,2606.89579999999 變?yōu)?26069.但是,我需要將數(shù)字四舍五入到小數(shù)點(diǎn)后兩位后面會(huì)有一個(gè)零,所以 2606.89579999999 應(yīng)該變成 260690.
I've been working on a script that takes data from an Excel spreadsheet, rounds the numbers, and removes the decimal point, for example, 2606.89579999999 becomes 26069. However, I need the number to round to two decimal places even if there would be a trailing zero, so 2606.89579999999 should become 260690.
我目前有它,所以 i
從 Excel 中的單元格中獲取數(shù)據(jù),并將其四舍五入到小數(shù)點(diǎn)后兩位 (i = round(i, 2)
)在上面的例子中給了我一個(gè)小數(shù)點(diǎn).
I currently have it so i
takes the data from the cell in Excel, and rounds it to two decimal places (i = round(i, 2)
) which gives me the single decimal point in the above example.
我已經(jīng)嘗試弄清楚如何讓它與 Decimal
一起工作,但我似乎無法讓它工作.
I've tried figuring out how to get this to work with Decimal
, but I can't seem to get it working.
所有其他四舍五入的數(shù)字,如果四舍五入的值不以0"結(jié)尾,則可以使用 round(i, 2)
,但如果數(shù)字恰好以*.x0,那個(gè) 0 被丟棄并與數(shù)據(jù)混淆.
All other numbers that get rounded, if the rounded value doesn't end in '0', work fine with round(i, 2)
, but if the numbers just so happen to end in *.x0, that 0 gets dropped off and messes with the data.
推薦答案
正如你所說的尾隨零,這是一個(gè)關(guān)于表示為字符串的問題,你可以使用
As you are talking about trailing zeros, this is a question about representation as string, you can use
>>> "%.2f" % round(2606.89579999999, 2)
'2606.90'
或者使用帶有format
功能的現(xiàn)代風(fēng)格:
Or use modern style with format
function:
>>> '{:.2f}'.format(round(2606.89579999999, 2))
'2606.90'
并用 replace
或 translate
刪除點(diǎn)(_
指 python 控制臺(tái)中先前命令的結(jié)果):
and remove point with replace
or translate
(_
refers to result of previous command in python console):
>>> _.translate(None, '.')
'260690'
注意這里不需要四舍五入,因?yàn)?.2f
格式應(yīng)用相同的四舍五入:
Note that rounding is not needed here, as .2f
format applyies the same rounding:
>>> "%.2f" % 2606.89579999999
'2606.90'
但正如您提到的 excel,您可能會(huì)選擇滾動(dòng)自己的舍入函數(shù),或使用 decimal,因?yàn)?float.round
會(huì)由于浮點(diǎn)表示而導(dǎo)致奇怪的結(jié)果:
But as you mentioned excel, you probably would opt to roll your own rounding function, or use decimal, as float.round
can lead to strange results due to float representation:
>>> round(2.675, 2)
2.67
>>> round(2606.89579999999, 2)
2606.89
使用小數(shù)量化:
>>> from decimal import *
>>> x = Decimal('2606.8950000000001')
# Decimal('2606.8950000000001')
>>> '{}'.format(x.quantize(Decimal('.01'), rounding=ROUND_HALF_EVEN))
'2606.90'
對于您的原始任務(wù),變?yōu)?
That, for your original task, becomes:
>>> x = Decimal('2606.8950000000001')
>>> int((x*100).quantize(1, rounding=ROUND_HALF_EVEN))
260690
Decimal
出現(xiàn)了奇怪的四舍五入的原因:
And the reason of strange rounding comes to the front with Decimal
:
>>> x = Decimal(2606.8950000000001)
# Decimal('2606.89499999999998181010596454143524169921875') # internal float repr
這篇關(guān)于在 Python 中舍入一個(gè)數(shù)字但保持結(jié)尾為零的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!