math.modf函数用于返回两个值,第一个值是数字的整数值,第二个返回值是数字的小数值(如果有的话)。
math.floor函数是向下取整函数。例如:
```lua
math.floor(5.123) -- 结果为5
math.floor(5.523) -- 结果为5
```
使用此特性可以实现四舍五入。例如:
```lua
math.floor(5.123 + 0.5) -- 结果为5
math.floor(5.523 + 0.5) -- 结果为6
```
对于小数精度截取,可以使用以下代码:
```lua
function GetPreciseDecimal(num, n)
if type(num) ~= "number" then
return num
end
n = n or 0
n = math.floor(n)
if n < 0 then n = 0 end
local decimal = 10 ^ n
local temp = math.floor(num * decimal)
return temp / decimal
end
```
获取一个数的位数可以使用以下代码:
```lua
function GetNumDigit(num)
local result = num
local digit = 0
while(result > 0) do
result = math.modf(result / 10)
digit = digit + 1
end
return digit
end
```
以下是重构后的代码:
```lua
function GetNumDigit(num)
local result = num
local digit = 0
while(result > 0) do
result = math.modf(result / 10)
digit = digit + 1
end
return digit
end
local num = 690
local digit = GetNumDigit(num)
print("digit:" .. digit)
local digit2 = digit - 2
print("digit2:" .. digit2)
local ten = math.pow(10, digit2)
print("ten:" .. ten)
local qianLiangWei = math.modf(num / ten)
print("qianLiangWei:" .. qianLiangWei)
local qianLiangWeiXiaoShu = qianLiangWei[1]
local qianLiangWeiXSZ, qianLiangWeiXSX = math.modf(qianLiangWeiXiaoShu)
print(qianLiangWeiXSZ .. "--" .. qianLiangWeiXSX)
function ShiSheLiuRu(XiaoShu, XiaoPart)
if XiaoPart == 0.5 then
return XiaoShu
else
return round(XiaoShu)
end
end
function round(value)
value = tonumber(value) or 0
return math.floor(value + 0.5)
end
local qianLiangWei5BeiShu = ShiSheLiuRu(qianLiangWeiXiaoShu, qianLiangWeiXSX)
print(qianLiangWei5BeiShu)
local final = qianLiangWei5BeiShu * ten * 10
print("final:".. final) --输出:digit:3 digit2:1 ten:10 qianLiangWei:696--->0.9777777778
```
以下是重构后的内容:
整数最靠近5的倍数
```lua
function GetDengJiZhengByNear5(num)
local geWei = num % 10
local zhengPart, xiaoPart = math.modf(num / 10)
local xiaoShu = num / 10
if geWei <= 2 then
return zhengPart * 10
elseif geWei >= 3 and geWei <= 7 then
return zhengPart * 10 + 5
elseif geWei >= 8 then
return round(xiaoShu) * 10
end
end
--四舍五入
function round(value)
value = tonumber(value) or 0
return math.floor(value + 0.5)
end
num = 59
print(GetDengJiZhengByNear5(num))
```
输出结果为60。