如何将浮点数四舍五入到小数点后一位? [英] How to round a floating point number up to a certain decimal place?
问题描述
假设我有8.8333333333333339
,并且我想将其转换为8.84
.如何在Python中完成此操作?
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)
给出8.83
,而不是8.84
.我是Python或一般编程的新手.
round(8.8333333333333339, 2)
gives 8.83
and not 8.84
. I am new to Python or programming in general.
我不想将其打印为字符串,结果将被进一步使用.有关此问题的更多信息,请检查 Tim Wilson的Python编程技巧:贷款和付款计算器 .
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
(或8.833333333333334
,106.00/12
的结果)正确舍入到小数点后两位是8.83
.在数学上,这听起来像是您想要的天花板功能. Python的math
模块中的一个名为 ceil
:
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
地板和天花板函数通常分别将实数映射到最大的前一个或最小的后整数,该整数具有小数点后零位-因此,将它们用于2个小数位,首先将数字乘以10 2 (或100)移动小数点,然后除以小数点以进行补偿.
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.
如果由于某种原因不想使用math
模块,则可以使用我刚刚写的这个(经过最低测试的)实现:
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
这如何适用于链接的贷款和付款计算器问题
从示例输出中可以看出,他们 四舍五入 每月付款,这就是所谓的上限功能的效果.这意味着每个月要支付的总额略多于 1 ⁄ 12 .这使得最终付款额比平时要少一些-剩余的未付余额仅为8.76
.
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
.
使用正常的四舍五入同样有效,它每月产生8.83
的付款,而最终产生的8.87
则稍高.但是,在现实世界中,人们通常不希望增加自己的付款,因此对每笔付款进行四舍五入是一种常见的做法-还会更快地将钱退还给贷方.
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.
这篇关于如何将浮点数四舍五入到小数点后一位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!