Lua中保留兩位小數

在使用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

local num1, num2 = 0.1234, 1.5678
print(num1 - num1 % 0.01, num2 - num2 % 0.01)
-- 0.12	1.56

-- 保留n位小數
function keepDecimalTest(num, n)
    if type(num) ~= "number" then
        return num    
    end
    n = n or 2
    return num - num % 0.1 ^ n
end
print(keepDecimalTest(num1, 3), keepDecimalTest(num2, 3))
-- 0.123	1.567

Tips

返回值的類型爲number

 

ps

string.format保留固定位數的小數的取捨規則是四捨五入?no,其實是四捨六入五成雙

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章