2016-05-14 105 views
2

对不起,我想不出更好的东西。所以我正在制作一个缩短数字(1000到1k)的函数,现在就是这样。大数字搞乱了?

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)) 

然后打印。

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

我打印一个零(缩短()),它工作正常。我假设数字太大,或者代码有问题。谢谢您阅读此篇。

+1

'tostring()'可能会出乎意料。例如,对于'num = 178900000000000''tostring(num)=“1.789e + 14”'。计算位数的更正确方法:'local len = math.ceil(math.log10(num + .5))' –

回答

1

tostring给人类可读的字符串表示,并且在你的例子一个大数目一样,它采用科学记数法:

print(tostring(178900000000000)) 

在Lua的5.2或更低,结果如果1.789e+14。在Lua 5.3中,由于新引入的整数子类型,结果如预期的那样为178900000000000,但对于更大的整数仍然会被破坏。