So i would like to achieve a way where instead of the text display it as numbers, the way you say numbers is like text, kind of like this:
how do i achieve this?
There is a way to use tonumber
, however, that only works if the string is a number. I am not sure how that would work with a string spelling it the number. Is there any way to change the spelling of it to a number initially? How are you able to get the spelling of it?
I presumed this wouldn’t be possible without having an extensive dictionary containing comprehensive number “spelling” translations depending on the number of digits, etc. OR by querying external APIs each time you’d like a number spelled.
Hence, after a bit of searching (purely out of curiosity), I came across this post that seems to to be handling this task with a fairly smart set of arithmetic operations which seems to be achieving what you’re looking for.
I’ve modified the function just slightly to check if the parsing parameter is a valid integer. See if this is what you’re looking for. Hope that helps.
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)
n = tonumber(n)
if n then
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
end
local int = IntegerNumberInWords(69000)
if int then
print(int.." dollars")
end
Oh. I read it wrong actually. Forget what I just said. How are you getting the number in the first place?
Works well and i love it, im gonna annoy so many people with this
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.