views:

121

answers:

1

How do pythonistas print a number as words, like the equivalent of the Common Lisp code:

[3]> (format t "~r" 1e25)
nine septillion, nine hundred and ninety-nine sextillion, nine hundred and ninety-nine quintillion, seven hundred and seventy-eight quadrillion, one hundred and ninety-six trillion, three hundred and eight billion, three hundred and sixty-one million, two hundred and sixteen thousand
+5  A: 

no in python core, but there is 3rd party library num2word

>>> num2word.to_card(1e25)
'ten septillion, one billion, seventy-three million, seven hundred and forty-one thousand, eight hundred and twenty-four'

>>> num2word.to_card(10000000000000000000000000)
'ten septillion'

(note that 1e25 is not converted to integer precisely, neither in your example)

mykhal
Excellent - I actually noticed that, but it's an error in how python (C?) handles the exponential expression: `int(1e25)` produces `10000000000000000905969664L` and `1*10**25` produces `10000000000000000000000000L`. Strange?
Wayne Werner
Not strange at all. `1e25` is "make the floating-point value closest to 10^25", and `1*10**25` says "multiply 1 by the result of multiplying 10 by itself 25 times". Fixed-width floating-point arithmetic (on a computer) is not mathematically precise, while integers in recent versions of Python are arbitrary-precision.
Ken
1e25 is not an "exponential expression", it's a floating point literal. And a floating point number in python cannot represent exactly 10**25 (and this shouldn't be such a big surprise given that 2**84 > 10**25 > 2**83).
6502
interesting and informative! Based on that information, I was curious and played around a bit, and if you want accuracy you can `import decimal; d = decimal.Decimal('1e25')` and you won't get the floating-point error.
Wayne Werner