Lua retains n decimal places

Since Markdown, I have moved some blogs here ~


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

Postscript: 2015/06/25

  • problem

string.format ("%. xf", nNum) will round nNum (same format as printf in C language). So this method is also problematic, please pay attention to it

Examples:

1. GetPreciseDecimal(0.38461538461538) =     0.4

2. The method of finding the remainder

    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

result:

2. GetPreciseDecimal(0.38461538461538) =     0.3

Question: under lua, there is a case of 0.7% 0.1 = 0.1, so the above writing is wrong

Examples:

2. GetPreciseDecimal(0.7) =     0.6

Solution: See 3. Amendment, do not use remainder method

3. Remainder method (revision)

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

test:

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

To be tested: I do not know if there are any other problems

4. Summary:

  • Be careful with the use of decimals in lua
Published 41 original articles · praised 7 · 20,000+ views

Guess you like

Origin blog.csdn.net/pkxpp/article/details/100109715