1、使用string.format转换,再通过tonumber转换回来
1 2 |
print(string.format("%.1f",0.26)) ---会自动四舍五入,输出0.3,而不是0.2 |
2、math计算方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
--- nNum 源数字 --- n 小数位数 function Tool.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、数字计算方式
使用%运算符,得到的结果是数字
x%1 表示x的小数部分,x-x%1 表示x的整数部分。
类似的,x-x%0.01 将x精确到小数点后2位。