lua保留n位小數方法


time:2015/04/21

1. string.format()

function GetPreciseDecimal(nNum, n)
    if type(nNum) ~= "number" then
        return nNum;
    end
    
    n = n or 0;
    n = math.floor(n)
    local fmt = '%.' .. n .. 'f'
    local nRet = tonumber(string.format(fmt, nNum))

    return nRet;
end

后記:2015/06/25

問題:string.format("%.xf", nNum)會對nNum進行四舍五入(同C語言中的printf的格式符一樣)。所以這種方法也是有問題的,用的人請注意

舉例:

1. GetPreciseDecimal(0.38461538461538) =     0.4

 

2. 求余的方法

function GetPreciseDecimal(nNum, n)
    if type(nNum) ~= "number" then
        return nNum;
    end
    n = n or 0;
    n = math.floor(n)
    if n < 0 then
        n = 0;
    end
    local nDecimal = 1/(10 ^ n)
    if nDecimal == 1 then
        nDecimal = nNum;
    end
    local nLeft = nNum % nDecimal;
    return nNum - nLeft;
end

結果:

2. GetPreciseDecimal(0.38461538461538) =     0.3

問題:在lua下面,存在0.7 % 0.1 = 0.1的情況,所以上面寫法錯誤

舉例:

2. GetPreciseDecimal(0.7) =     0.6

解決:見3.修訂,不使用求余方法

3. 求余方法(修訂)

function GetPreciseDecimal(nNum, n)
    if type(nNum) ~= "number" then
        return nNum;
    end
    n = n or 0;
    n = math.floor(n)
    if n < 0 then
        n = 0;
    end
    local nDecimal = 10 ^ n
    local nTemp = math.floor(nNum * nDecimal);
    local nRet = nTemp / nDecimal;
    return nRet;
end

測試:

3. GetPreciseDecimal(0.38461538461538) =     0.7
3. GetPreciseDecimal(0.7) =     0.7

待測:不知道還有沒有其他問題

4. 總結:

(1)小心lua里面的小數使用方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM