简体   繁体   English

python 2.7强制将小数点后两位取整

[英]python 2.7 force round up 2 decimal places

I'm trying to force a float to round up to the 2nd decimal place. 我正在尝试强制将浮点数舍入到小数点后两位。 I know this isn't the best practice, but it's what I need for a program I'm working on. 我知道这不是最佳做法,但这是我正在开发的程序所需要的。 So for example: 因此,例如:

100.00 = 100.00 100.00 = 100.00

100.001 = 100.01 100.001 = 100.01

100.009 = 100.01 100.009 = 100.01

I've gotten pretty close to the results i need with math.ceil and a tip i read in another post, but am running into an issue where if the input number already ends exactly in 2 decimal places, it's rounding up unnecessarily. 我已经接近math.ceil所需的结果,并且在另一篇文章中读到了一个提示,但是遇到了一个问题,即如果输入数字已经精确地以小数点后两位放在小数点后,它会四舍五入。 Here is an example: 这是一个例子:

import math

taxpcnt = 1.12
roomsubtotal = 699.00

roomttl = math.ceil(taxpcnt * roomsubtotal * 100) / 100

print roomttl

This I would think would return 782.88, since 699 * 1.12 is exactly 782.88, but instead it returns 782.89. 我认为这将返回782.88,因为699 * 1.12恰好是782.88,但是它返回了782.89。 Weirder is if i 'print taxpcnt * roomsubtotal', i get 782.88. 怪异的是,如果我“打印taxpcnt * roomsubtotal”,我会得到782.88。 If i change the code to: 如果我将代码更改为:

roomttl = math.ceil(782.88 * 100) / 100

I get the correct value. 我得到正确的值。 But some reason, all together it's not calculating right. 但是由于某些原因,总的来说计算不正确。

Any tips on how to properly get what I'm trying to achieve? 关于如何正确获得我要达到的目标的任何提示?

Edit: I think I have patched together a solution: 编辑:我想我已经修补了一个解决方案:

import math

taxpcnt = 1.12
roomsubtotal = 699.00

rate = "%.2f" % (taxpcnt * roomsubtotal * 100)
rate = float(rate)

roomttl = math.ceil(rate) / 100

Not sure if this is the best method, but at least it seems to work. 不知道这是否是最好的方法,但至少它似乎有效。

Welcome to the world of floating point. 欢迎来到浮点世界。 Have a read of this to get an idea of what's going on. 有一个读得到什么事情的想法。

The result of 699 * 1.12 cannot be accurately represented by the computer, so the rounded result is incorrect. 699 * 1.12的结果无法由计算机准确表示,因此四舍五入的结果不正确。

>>> 699 * 1.12
782.8800000000001

If you only care about two decimal places consider using a different type, such as a Decimal . 如果只关心小数点后两位,请考虑使用其他类型,例如Decimal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM