2016-05-14 15 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 

私は印刷物(shorten())を1つ取り除いて正常に動作します。数字が大きすぎると仮定しているか、コードに問題がある可能性があります。これを読んでいただきありがとうございます。

+1

'tostring()'は予期しないことがあります。たとえば、 'num = 178900000000000'の場合、tostring(num)=" 1.789e + 14 "'となります。数字の桁数を計算するより正確な方法: 'local len = math.ceil(math.log10(num + .5))' –

答えて

1

tostringが判読できる文字列表現を与え、あなたの例のように、大きな数のために、それは科学的表記法を使用しています:Luaの5.2以下で

print(tostring(178900000000000)) 

、結果を1.789e+14場合。 Lua 5.3では、新たに導入された整数サブタイプのため、結果は期待どおりに178900000000000になりますが、さらに大きな整数の場合でも引き続き破損します。

関連する問題