我的環境:Unity3D 5.3.7p4
XLua版本v2.1.6 基於Lua5.3 (https://github.com/Tencent/xLua)
在Lua中數字不區分整型或浮點型,所有都是number,當你在整除時,返回的結果中帶有小數0,比如printf(100/10 ) ---輸出10.0
注意:在Lua5.1.4的控制台模式,並不會出現此問題。如果輸入100/10,則會打印出10,而不是10.0
數字函數
local n1,n2 = math.modf(x)
:返回兩個值,第一個為整數部分,第二個為小數部分
示例:local t1, t2 = math.modf(3.2) ---t1=3,t2=0.2
示例和格式化方法
Util.FormatNum(10/100) ---輸出10
Util.FormatNum(0.1) ---輸出0.1
---如果小數位數為0,則只保留整數
function Util.FormatNum (num)
if num <= 0 then
return 0
else
local t1, t2 = math.modf(num)
---小數如果為0,則去掉
if t2 > 0 then
return num
else
return t1
end
end
end
Lua 5.1和5.3的對比
下圖中,左邊為Lua5.1,右邊為5.3,結果說明:Lua5.1並不會出現此問題,而5.3則會有。