How to round a floating point number up to a certain decimal place?(如何将浮点数四舍五入到某个小数位?)
问题描述
假设我有 8.8333333333333339
,我想将其转换为 8.84
.如何在 Python 中完成此操作?
round(8.8333333333333339, 2)
给出 8.83
而不是 8.84
.我是 Python 或一般编程新手.
我不想把它打印成字符串,结果会被进一步使用.有关该问题的更多信息,请查看
从示例输出看来,他们四舍五入每月付款,这就是许多人所说的上限函数的效果.这意味着每个月支付的总金额略多于 1⁄12.这使得最后的付款比平时少了一点——剩下的未付余额只有 8.76
.
使用正常舍入产生 8.83
的每月付款和 8.87
稍高的最终付款同样有效.然而,在现实世界中,人们通常不喜欢他们的付款增加,因此将每笔付款四舍五入是常见的做法——它也可以更快地将钱还给贷方.
Suppose I have 8.8333333333333339
, and I want to convert it to 8.84
. How can I accomplish this in Python?
round(8.8333333333333339, 2)
gives 8.83
and not 8.84
. I am new to Python or programming in general.
I don't want to print it as a string, and the result will be further used. For more information on the problem, please check Tim Wilson's Python Programming Tips: Loan and payment calculator.
8.833333333339
(or 8.833333333333334
, the result of 106.00/12
) properly rounded to two decimal places is 8.83
. Mathematically it sounds like what you want is a ceiling function. The one in Python's math
module is named ceil
:
import math
v = 8.8333333333333339
print(math.ceil(v*100)/100) # -> 8.84
Respectively, the floor and ceiling functions generally map a real number to the largest previous or smallest following integer which has zero decimal places — so to use them for 2 decimal places the number is first multiplied by 102 (or 100) to shift the decimal point and is then divided by it afterwards to compensate.
If you don't want to use the math
module for some reason, you can use this (minimally tested) implementation I just wrote:
def ceiling(x):
n = int(x)
return n if n-1 < x <= n else n+1
How all this relates to the linked Loan and payment calculator problem:
From the sample output it appears that they rounded up the monthly payment, which is what many call the effect of the ceiling function. This means that each month a little more than 1⁄12 of the total amount is being paid. That made the final payment a little smaller than usual — leaving a remaining unpaid balance of only 8.76
.
It would have been equally valid to use normal rounding producing a monthly payment of 8.83
and a slightly higher final payment of 8.87
. However, in the real world people generally don't like to have their payments go up, so rounding up each payment is the common practice — it also returns the money to the lender more quickly.
这篇关于如何将浮点数四舍五入到某个小数位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将浮点数四舍五入到某个小数位?


基础教程推荐
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 包装空间模型 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01