savoirfairelinux / num2words

Modules to convert numbers to words. 42 --> forty-two
GNU Lesser General Public License v2.1
823 stars 496 forks source link

Wrong float interpretation #1

Closed camilonova closed 10 years ago

camilonova commented 11 years ago

I'm running the example as:

num2words(11)
u'eleven'

And then:

num2words(11.10)
u'eleven point zero nine'

Somehow there is a rounding somewhere doing it wrong.

ghost commented 11 years ago

I didn't even know that num2words supported floats :)

I could verify the bug, but I suspect that it's linked to the imprecision inherent to how floats are implemented in Python 2.x. For example, I don't have the same problem in this case:

>>> from decimal import Decimal
>>> num2words(Decimal('11.10'))
u'eleven point one zero'
>>> 

Still worth checking out, but I suspect it's a tricky fix.

pfortes commented 10 years ago

You are right, converting a float to string and then aplying Decimal to it rounds it correctly for num2words:

from num2words import num2words
from decimal import Decimal

request.total = 1838.0399999999999636202
total = num2words(Decimal(str(request.total)), lang='es')

Result: 1838.04 = mil ochocientos treinta y ocho punto cero cuatro

ghost commented 10 years ago

So yeah, I guess that the only possible answer to that request is "use Decimal". I don't think that there's much else to do.

camilonova commented 10 years ago

You can always use https://github.com/AxiaCore/number-to-letters