crookedleaf
crookedleaf

Reputation: 2198

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.001 = 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. 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. Weirder is if i 'print taxpcnt * roomsubtotal', i get 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.

Upvotes: 0

Views: 1257

Answers (1)

Tim
Tim

Reputation: 12174

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
782.8800000000001

If you only care about two decimal places consider using a different type, such as a Decimal.

Upvotes: 1

Related Questions