CJ.
CJ.

Reputation: 75

Large numbers messing up?

Sorry about the bad title, I couldn't think of anything better. So I was making a function to shorten numbers(1000 to 1k) and here it is.

local letters = {
"K",
"M", --I'm too lazy to put more
"B",
"QD",
"QN",
}
local nums = {}

for q=1,#letters do
    local dig = (q*3)+1
    local letter = 1*(10^(dig-1))
    table.insert(nums,#nums+1,letter)
end


function shorten(num)
local len = tostring(num):len()
print(len)
if len>=4 then
    for q=1,#letters do
        local dig = (q*3)+1 --digits the letter is
        if len <= dig+2 then
            local toDo = math.floor(num/nums[q])
            print(nums[q])
            local newNum = toDo..letters[q]
            return newNum
            end
        end
    end
end

print(shorten(178900000000000))

And this prints.

10 --the length, and the real length of it is 15
1000000000 --the one to divide it
178900B --shortened num

I take one zero off of the print(shorten()) and it works fine. And I'm assuming the numbers are too big, or maybe there's a problem with the code. Thank you for reading this.

Upvotes: 2

Views: 94

Answers (1)

Yu Hao
Yu Hao

Reputation: 122443

tostring gives the human-readable string representation, and for a big number like in your example, it uses scientific notation:

print(tostring(178900000000000)) 

In Lua 5.2 or lower, the result if 1.789e+14. In Lua 5.3, because of the newly introduced integer subtype, the result is 178900000000000 as expected, but it would still be broken for even bigger integers.

Upvotes: 1

Related Questions