Skip to content

Instantly share code, notes, and snippets.

@hjpotter92
Last active January 22, 2017 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hjpotter92/8a4ec34b1c58dadf74a1 to your computer and use it in GitHub Desktop.
Save hjpotter92/8a4ec34b1c58dadf74a1 to your computer and use it in GitHub Desktop.
Convert a number to equivalent string representation
NumberToString = (function ()
local insert, concat, floor, abs = table.insert, table.concat, math.floor, math.abs
local num, tens, bases = {
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten',
'eleven',
'twelve',
'thirteen',
'fourteen',
'fifteen',
'sixteen',
'seventeen',
'eighteen',
'nineteen'
}, {
[2] = 'twenty',
[3] = 'thirty',
[4] = 'forty',
[5] = 'fifty',
[6] = 'sixty',
[7] = 'seventy',
[8] = 'eighty',
[9] = 'ninety',
}, {
{ 10^12, ' trillion' },
{ 10^9, ' billion' },
{ 10^6, ' million' },
{ 10^3, ' thousand' },
{ 10^2, ' hundred' },
}
return function(n, pretty)
if pretty == nil then
pretty = true
end
local str = {}
if n < 0 then
insert( str, "minus" )
elseif n == 0 then
return "zero"
end
n = floor( abs(n) )
if n > 10^15 then
insert( str, "infinity" )
else
local AND
for _, base in ipairs(bases) do
local value = base[1]
if n >= value then
insert( str, NumberToString(n / value)..base[2] )
n, AND = n % value, pretty
end
end
if n > 0 then
if AND then
insert( str, "and" )
end
insert( str, num[n] or tens[floor(n/10)]..(n % 10 > 0 and '-'..num[n % 10] or '') )
end
end
return concat(str, ' ')
end
end)()
from math import *
num, tens, bases = [
'',
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten',
'eleven',
'twelve',
'thirteen',
'fourteen',
'fifteen',
'sixteen',
'seventeen',
'eighteen',
'nineteen',
'twenty'
], [
'',
'',
'',
'thirty',
'forty',
'fifty',
'sixty',
'seventy',
'eighty',
'ninety',
], [
(10**12, ' trillion'),
(10**9, ' billion'),
(10**6, ' million'),
(10**3, ' thousand'),
(10**2, ' hundred')
]
t = len(num)
def NumberToString(n):
n, s = int( floor(abs(n)) ), ()
if n <= t:
return num[n]
for i in bases:
if n >= i[0]:
x = NumberToString(n / i[0])
s += ( x + i[1], )
n = int( n % i[0] )
if n <= t:
s += ( num[n], )
else:
s += ( tens[int(floor(n / 10))] + ' ' + num[n % 10], )
return ' '.join(s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment