天天看點

Lua:小數精度計算,幾位數判斷,四舍五入,最靠近5倍數取整

math.modf

當我們調用該函數時,該函數傳回兩個值,第一個值是數字的整數值,第二個傳回值是數字的小數值(如果有的話)

math.floor

小數精度截取

--擷取準确小數
  -- num 源數字
  --n 位數
  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      

擷取一個數的位數

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      

整數4舍6入,5保留

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 = 10 ^ digit2
print(" ten:" ..  ten)
local qianLiangWei = math.modf(num / ten)
print("qianLiangWei:" .. qianLiangWei)

local qianLiangWeiXiaoShu = qianLiangWei/10
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 finial = qianLiangWei5BeiShu * ten * 10
print (finial)

--輸出
digit:3
digit2:1
 ten:10
qianLiangWei:69
6-->0.9
7
700      

整數最靠近5的倍數

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