round() to nearest .05 ?
Kent Johnson
kent3737 at yahoo.com
Mon Nov 15 16:46:04 EST 2004
tertius wrote:
> Hi,
>
> I'm trying to round my float total to the nearest .05 cents.
If you want the *nearest* .05, this works:
>>> def fivecents(f):
... return round(f*2.0, 1) / 2.0
...
>>> for f in [ 12.01, 0.14, 2.28, 703.81]:
... print f, fivecents(f)
...
12.01 12.0
0.14 0.15
2.28 2.3
703.81 703.8
> 12.01 should produce 12.00
> 0.14 should produce 0.10
> 2.28 " 2.25
> 703.81 " 703.80
Your example seems to be rounding down always, not what I would call
nearest. Here is one that always rounds toward zero:
>>> def lowerfivecents(f):
... return int(f*20) / 20.0
...
>>> for f in [ 12.01, 0.14, 2.28, 703.81]:
... print f, lowerfivecents(f)
...
12.01 12.0
0.14 0.1
2.28 2.25
703.81 703.8
If you want to always round toward more negative, use math.floor()
instead of int().
Kent
>
> "%.02f"%100.0099 produces 100.01 (which I know is right)
> No combination of round and/or "%.02f" works for me.
>
> What's the best way to get there? Should I write a function to manage my
> rounding or is there a simpler/better way?
>
> TIA
> T
More information about the Python-list
mailing list