背景介绍
lua math库有 向下取整函数 math.floor , 有向上取整的函数 math.ceil,但没有内置四舍五入的函数。
而我们在业务开发中,不管是向上取整还是向下取整,需要面临精度问题,如果业务复杂度高,运算过程长且复杂的话,还得统一到底是向上取整还是向下取整。这时候如果有个四舍五入的函数支持,是不是更友好点,不需要再去关心因向上取整儿带来的精度问题。
函数实现
function mathRound(num)
if num > 0 then
return math.floor( num + 0.5 )
end
return math.ceil( num - 0.5 )
end
四舍五入round函数拓展到math库
function math.round(num)
if num > 0 then
return math.floor( num + 0.5 )
end
return math.ceil( num - 0.5 )
end
--使用举例
print( math.round(1.2) )
print( math.round(1.6) )
输出:
1
2


文章介绍了Lua中的math库缺失四舍五入函数,提出了一种自定义math.round函数的实现方法,通过在math.floor和math.ceil基础上进行调整,解决了业务开发中的精度问题。作者给出了函数实现及使用示例。
4572

被折叠的 条评论
为什么被折叠?



