2016-05-14 90 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,但對於更大的整數仍然會被破壞。