Juno Bijlard
Juno Bijlard

Reputation: 13

Printing values in iPython

I've defined a class containing attributes and a print function, which prints the attributes of the class to the console. If I call the printing function like: object.printing_function() the desired value is printed, e.g. 0.24

However, when I access the attribute from without the class, like: object.attribute, the returned value is 0.23999999999999.

Print(object.attribute) gives 0.24 as well, how can I change the object.attribute to return 0.24?

I'm using: Spyder (Anaconda) Python 3.5

Upvotes: 1

Views: 2993

Answers (3)

Carlos Cordoba
Carlos Cordoba

Reputation: 34136

I think what you need is the IPython precision magic:

https://ipython.org/ipython-doc/3/interactive/magics.html#magic-precision

For example, writing this command in an IPython console:

In [2]: %precision 3

you make all numbers afterwards to be printed with 3 floating point digits.

Upvotes: 1

Tyler
Tyler

Reputation: 91

You can use the Decimal class which can represent decimal numbers exactly:

>>> import decimal
>>> print('{:.20f}'.format(0.24))
0.23999999999999999112
>>> print('{:.20f}'.format(decimal.Decimal('0.24')))
0.24000000000000000000

As the comments point out, 0.24 as a float cannot be represented exactly in binary, just as 1/3 can't be represented exactly in decimal.

Upvotes: 1

aquil.abdullah
aquil.abdullah

Reputation: 3157

If the attribute is a floating point number you'll have to format the output if you are accessing the attribute directly:

val = 0.23999999999999
print("{:.2f}".format(val))

# Output
# '0.24'

Upvotes: 0

Related Questions