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里面的小数使用方法

posted @   上山老人  阅读(26622)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤
点击右上角即可分享
微信分享提示