-
-
Save Egor-Skriptunoff/1cf4070c7532db0f8ce0b875717801d8 to your computer and use it in GitHub Desktop.
Spell number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local append, concat, floor, abs = table.insert, table.concat, math.floor, math.abs | |
local num = {'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', | |
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'} | |
local tens = {'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'} | |
local bases = {{floor(1e18), ' quintillion'}, {floor(1e15), ' quadrillion'}, {floor(1e12), ' trillion'}, | |
{floor(1e9), ' billion'}, {1000000, ' million'}, {1000, ' thousand'}, {100, ' hundred'}} | |
local insert_word_AND = false -- 101 = "one hundred and one" / "one hundred one" | |
local function IntegerNumberInWords(n) | |
-- Returns a string (spelling of integer number n) | |
-- n should be from -2^53 to 2^53 (-2^63 < n < 2^63 for integer argument in Lua 5.3) | |
local str = {} | |
if n < 0 then | |
append(str, "minus") | |
end | |
n = floor(abs(n)) | |
if n == 0 then | |
return "zero" | |
end | |
if n >= 1e21 then | |
append(str, "infinity") | |
else | |
local AND | |
for _, base in ipairs(bases) do | |
local value = base[1] | |
if n >= value then | |
append(str, IntegerNumberInWords(n / value)..base[2]) | |
n, AND = n % value, insert_word_AND or nil | |
end | |
end | |
if n > 0 then | |
append(str, AND and "and") -- a nice pun ! | |
append(str, num[n] or tens[floor(n/10)-1]..(n%10 ~= 0 and '-'..num[n%10] or '')) | |
end | |
end | |
return concat(str, ' ') | |
end | |
-- Usage: | |
-- print(IntegerNumberInWords(-12345)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment