Hi. I have an issue who i can't solve.

The problem is that a = "13.33" and I want it to turn a = 13.33 and not 13.3333333333 and not 13.330000002.

So, how do i make it so "13.33" will be an 13.33 float?

I do not see problem for that:

>>> a='13.33'
>>> a=float(a)
>>> a
13.33
>>> print(a-13.33)
0.0
>>>

I do not see problem for that:

>>> a='13.33'
>>> a=float(a)
>>> a
13.33
>>> print(a-13.33)
0.0
>>>

But test this.

>>> new = "18,33"
>>> a = new.replace(",",".")
>>> a
'18.33'
>>> a = float(a)
>>> a
18.329999999999998
>>>

It must be 18.33.

It is:

Python 3.2.1 (default, Jul 10 2011, 21:51:15) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> new = '18.33'
>>> new = '18,33'
>>> a = new.replace(',', '.')
>>> a
'18.33'
>>> a = float(a)
>>> a
18.33
>>>
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> new = '18,33'
>>> a = new.replace(',', '.')
>>> a
'18.33'
>>> a = float(a)
>>> a
18.33
>>>

There some interesting builtin methods for floating point numbers by the way:

>>> a=18.33
>>> a.as_integer_ratio()
(1289859080776581L, 70368744177664L)
>>> a.hex()
'0x1.2547ae147ae14p+4'
>>>

It is:

Python 3.2.1 (default, Jul 10 2011, 21:51:15) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> new = '18.33'
>>> new = '18,33'
>>> a = new.replace(',', '.')
>>> a
'18.33'
>>> a = float(a)
>>> a
18.33
>>>
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> new = '18,33'
>>> a = new.replace(',', '.')
>>> a
'18.33'
>>> a = float(a)
>>> a
18.33
>>>

>>> new = '18,33'
>>> a = new.replace(',','.')
>>> a
'18.33'
>>> a = float(a)
>>> a
18.329999999999998
>>>

: S

Is it's impossible?

Since the floating point representation uses 64 bits, it can only represent 2 ** 64, about 18 billion billion numbers. Since there is an uncountable infinity of real numbers, almost all of them must be approximated. So, yes, for most numbers, it's impossible. Also notice that for many problems, this precision suffices.

Edited 5 Years Ago by Gribouillis: n/a

This article has been dead for over six months. Start a new discussion instead.