lua保留n位小数方法

自从有了markdown,陆续把一些博客搬到这里来了~


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. 总结:

  • 小心lua里面的小数使用方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值