如何从 Lua 中的浮点数中仅获取小数部分?

我如何能够完成以下操作?

local d = getdecimal(4.2) --> .2
点赞
用户3979429
用户3979429

假设您只使用大于0的数字,取模运算是最好的方法:

print(4.2%1)

否则,可以使用数学库中的fmod函数。

print(math.fmod(4.2,1))
2016-02-01 01:18:44
用户4204364
用户4204364
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)
2016-02-01 01:37:52
用户3924687
用户3924687

你可以采用一种非典型的方法,将数字转化为字符串:

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

print(getDec(-3.2))
--2
2016-02-01 03:40:41