# floating point rounding

Discussion in 'Python' started by hg, Mar 9, 2007.

1. ### hgGuest

Hi,

Here is my issue:

f = 1.5 * 0.01
f
>> 0.014999999999999999

'%f' % f
>>'0.015000'

But I really want to get 0.02 as a result ... is there a way out ?

Thanks,

hg

hg, Mar 9, 2007

2. ### hgGuest

hg wrote:

> Hi,
>
> Here is my issue:
>
> f = 1.5 * 0.01
> f
>>> 0.014999999999999999

> '%f' % f
>>>'0.015000'

>
>
> But I really want to get 0.02 as a result ... is there a way out ?
>
> Thanks,
>
> hg

round

hg, Mar 9, 2007

3. ### hgGuest

John Henry wrote:

> On Mar 9, 5:45 am, hg <> wrote:
>> hg wrote:
>> > Hi,

>>
>> > Here is my issue:

>>
>> > f = 1.5 * 0.01
>> > f
>> >>> 0.014999999999999999
>> > '%f' % f
>> >>>'0.015000'

>>
>> > But I really want to get 0.02 as a result ... is there a way out ?

>>
>> > Thanks,

>>
>> > hg

>>
>> round

>
>
> Or more precisely:
>
> round(0.014999999999999999,2)
>
> if that's what you wish to do.

Indeed.

hg

hg, Mar 9, 2007
4. ### John HenryGuest

On Mar 9, 5:45 am, hg <> wrote:
> hg wrote:
> > Hi,

>
> > Here is my issue:

>
> > f = 1.5 * 0.01
> > f
> >>> 0.014999999999999999

> > '%f' % f
> >>>'0.015000'

>
> > But I really want to get 0.02 as a result ... is there a way out ?

>
> > Thanks,

>
> > hg

>
> round

Or more precisely:

round(0.014999999999999999,2)

if that's what you wish to do.

John Henry, Mar 9, 2007
5. ### gregGuest

John Henry wrote:

> Or more precisely:
>
> round(0.014999999999999999,2)

No, that *won't* solve the problem. Using a slightly
different example,

>>> x = 1.5 * 0.1
>>> x

0.15000000000000002
>>> round(x, 2)

0.14999999999999999

The problem is that floats are stored internally in
binary, not decimal, and numbers like 0.1 and 0.01
have no exact representation as a binary float.
Using round() doesn't help, because the result is
still a binary float, and the result you're after
still can't be represented.

The best you can do is to *display* it rounded
to the number of digits you want using formatting,
e.g.

>>> "%.2f" % x

'0.15'

Alternatively, use the Decimal module, which stores
numbers as decimal and does arithmetic in ways that
will match your calculator. It's slower, though.

--
Greg

greg, Mar 10, 2007