如何四舍五入浮点数达到某个小数位? [英] How to round a floating point number up to certain decimal place?

查看:150
本文介绍了如何四舍五入浮点数达到某个小数位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 8.8333333333333339 ,我想将它转换为 8.84 ,我怎么能在python ? round(8.8333333333333339,2)给出 8.83 而不是 8.84 。我是新的python或编程的一般。

我不想打印它作为一个字符串,结果将被进一步使用。有关该问题的更多信息,请查阅



从示例输出看来, 四舍五入 8.76 。



同样有效的是使用正常的四舍五入来产生每月支付 8.83 和稍高于 8.87 的最终支付。然而,在现实世界中,人们通常不喜欢支付他们的付款,所以每次付款都是一种常见的做法 - 它也可以更快地将钱还给贷款人。

Suppose I am having 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, 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 this applies 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 112 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.

这篇关于如何四舍五入浮点数达到某个小数位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆