在 Python 中舍入一个数字但保持结尾为零

时间:2022-11-29
本文介绍了在 Python 中舍入一个数字但保持结尾为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在编写一个脚本,该脚本从 Excel 电子表格中获取数据,对数字进行四舍五入并删除小数点,例如,2606.89579999999 变为 26069.但是,我需要将数字四舍五入到小数点后两位后面会有一个零,所以 2606.89579999999 应该变成 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 中的单元格中获取数据,并将其四舍五入到小数点后两位 (i = round(i, 2))在上面的例子中给了我一个小数点.

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.

我已经尝试弄清楚如何让它与 Decimal 一起工作,但我似乎无法让它工作.

I've tried figuring out how to get this to work with Decimal, but I can't seem to get it working.

所有其他四舍五入的数字,如果四舍五入的值不以0"结尾,则可以使用 round(i, 2),但如果数字恰好以*.x0,那个 0 被丢弃并与数据混淆.

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.

推荐答案

正如你所说的尾随零,这是一个关于表示为字符串的问题,你可以使用

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功能的现代风格:

Or use modern style with format function:

>>> '{:.2f}'.format(round(2606.89579999999, 2))
'2606.90'

并用 replacetranslate 删除点(_ 指 python 控制台中先前命令的结果):

and remove point with replace or translate (_ refers to result of previous command in python console):

>>> _.translate(None, '.')
'260690'

注意这里不需要四舍五入,因为 .2f 格式应用相同的四舍五入:

Note that rounding is not needed here, as .2f format applyies the same rounding:

>>> "%.2f" % 2606.89579999999
'2606.90'

但正如您提到的 excel,您可能会选择滚动自己的舍入函数,或使用 decimal,因为 float.round 会由于浮点表示而导致奇怪的结果:

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

使用小数量化:

>>> from decimal import *
>>> x = Decimal('2606.8950000000001')
# Decimal('2606.8950000000001')
>>> '{}'.format(x.quantize(Decimal('.01'), rounding=ROUND_HALF_EVEN))
'2606.90'

对于您的原始任务,变为:

That, for your original task, becomes:

>>> x = Decimal('2606.8950000000001')
>>> int((x*100).quantize(1, rounding=ROUND_HALF_EVEN))
260690

Decimal 出现了奇怪的四舍五入的原因:

And the reason of strange rounding comes to the front with Decimal:

>>> x = Decimal(2606.8950000000001)
# Decimal('2606.89499999999998181010596454143524169921875') # internal float repr

这篇关于在 Python 中舍入一个数字但保持结尾为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:将浮点数转换为位置格式的字符串(没有科学记数 下一篇:为什么浮点上的简单数学运算会在 VB.Net 和 Pyth

相关文章

最新文章