Luaは小数点以下n桁を保持します

Markdown以来、いくつかのブログをここに移動しました〜


時間: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.まとめ:

  • luaでの小数の使用に注意してください
41件のオリジナル記事を公開 賞賛7 20,000回以上の閲覧

おすすめ

転載: blog.csdn.net/pkxpp/article/details/100109715