在使用Lua进行开发的时候,经常会遇到保留n位小数的问题,这里以保留两位小数为例,记录一下需要注意的地方!

在选择处理方案之前,首先要确认需求,搞清楚保留两位小数是指小数点后第三位四舍五入还是从小数点后第三位开始直接舍去!

Case 1

Desc

小数点后第三位四舍五入

Method

string.format("%.2f", num)

Demo

local num1, num2 = 0.1234, -1.5678
print(string.format("%.2f", num1), string.format("%.2f", num2))
-- 0.12    -1.57

-- 保留n位小数
function keepDecimalTest(num, n)
    if type(num) ~= "number" then
        return num    
    end
    n = n or 2
    return string.format("%." .. n .. "f", num)
end
print(keepDecimalTest(num1, 3), keepDecimalTest(num2, 3))
-- 0.123   -1.568

Tips

string.format返回值的类型为string

 

Case 2

Desc

从小数点后第三位开始直接舍去

Method

num - num % 0.01

Demo

-- 保留n位小数
function keepDecimalTest(num, n)
    if type(num) ~= "number" then
        return num    
    end
    n = n or 2
    if num < 0 then
        return -(math.abs(num) - math.abs(num) % 0.1 ^ n)
    else
        return num - num % 0.1 ^ n
    end
end

local num1, num2 = 0.1234, -1.5678
print(keepDecimalTest(num1, 2), keepDecimalTest(num1, 3), keepDecimalTest(num2, 2), keepDecimalTest(num2, 3))
-- 0.12    0.123   -1.56   -1.567

Tips

返回值的类型为number

 

ps

string.format保留固定位数的小数的取舍规则是四舍五入?no,其实是四舍六入五成双

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐