2016-02-01 126 views
1

我將如何做到以下幾點?我怎樣才能得到lua浮點數的小數?

local d = getdecimal(4.2) --> .2 
+1

'math.fmod(4.2,1)'。如果你對負數不感興趣,你也可以使用模運算符:'4.2%1'。 – siffiejoe

+2

我投票結束這個問題作爲題外話,因爲你甚至沒有絲毫努力來解決這個問題。 –

+0

@NicolBolas對不起,但我不太擅長這種東西 – chabad360

回答

4

假設你只用數字大於0的工作,模量是最好的一段路要走:

print(4.2%1) 

否則在數學庫的FMOD功能應該做的伎倆。

print(math.fmod(4.2,1)) 
+0

需要注意的是,模運算符'%'將始終返回一個正數,而'fmod'則不會。 – Matthew

+0

@Matthew「假設你只使用大於0的數字」 – warspyking

+0

因此,「注意事項」這個詞組,它是關於兩者之間差異的更多信息。 – Matthew

-1
function getDecimal(inp) 
local x = tostring(inp) 
local found_decimal = false 
local output_stream = "" 
    for i = 1, string.len(x) do 
    if found_decimal == false then 
     if string.sub(x, i+1, i+1) == "." then 
     found_decimal = true 
     end 
    else 
    output_stream = output_stream .. string.sub(x,i, i) 
    end 
    end 
return output_stream 
end 

,做什麼是它發現一個字符串的小數點後它基本上返回的一切。

如果要打開返回回一批這樣做:採取數量,把它變成一個字符串

return tonumber("0" .. output_stream) 
1

你可以採取非範式的方式一點點這個:

function getDec(num) 
return tostring(num):match("%.(%d+)") 
end 

print(getDec(-3.2)) 
--2