前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Lua:小数精度计算,几位数判断,四舍五入,最靠近5倍数取整

Lua:小数精度计算,几位数判断,四舍五入,最靠近5倍数取整

作者头像
立羽
发布2023-08-24 15:40:35
3850
发布2023-08-24 15:40:35
举报
文章被收录于专栏:Unity3d程序开发Unity3d程序开发

math.modf

当我们调用该函数时,该函数返回两个值,第一个值是数字的整数值,第二个返回值是数字的小数值(如果有的话)

math.floor

向下取整 ua 中的math.floor函数是向下取整函数。 math.floor(5.123)  – 5 math.floor(5.523)   – 5 用此特性实现四舍五入 math.floor(5.123 + 0.5)  – 5 math.floor(5.523 + 0.5)  – 6 也就是对math.floor函数的参数进行 “+ 0.5” 计算

小数精度截取

代码语言:javascript
复制
	--获取准确小数
	-- num 源数字
	--n 位数
	function GetPreciseDecimal(num, n)
		if	type(num) ~= "number" then
			return num
		end
		n = n or 0
		n = math.floor(n)
		if	n < 0 then n = 0 end
		local decimal = 10 ^ n
		local temp = math.floor(num * decimal)
		return = temp / decimal
	end

获取一个数的位数

代码语言:javascript
复制
function GetNumDigit(num)
    local result = num
    local digit = 0
    while(result > 0) do
        result =math.modf(result / 10)
        digit = digit +1
    end
    return digit
end

整数4舍6入,5保留

例如从第二位开始算

代码语言:javascript
复制
function GetNumDigit(num)
    local result = num
    local digit = 0
    while(result > 0) do
        result =math.modf(result / 10)
        digit = digit +1
    end
    return digit
end

local num =690

local digit = GetNumDigit(num)
print("digit:" .. digit)
local digit2 = digit - 2
print("digit2:" .. digit2)
local ten = 10 ^ digit2
print(" ten:" ..  ten)
local qianLiangWei = math.modf(num / ten)
print("qianLiangWei:" .. qianLiangWei)

local qianLiangWeiXiaoShu = qianLiangWei/10
local qianLiangWeiXSZ,qianLiangWeiXSX =math.modf(qianLiangWeiXiaoShu)
print(qianLiangWeiXSZ .. "-->" .. qianLiangWeiXSX)

function ShiSheLiuRu(XiaoShu,XiaoPart)
	if XiaoPart == 0.5 then
		return XiaoShu
	else
		return 	round(XiaoShu)
	end
end


--四舍五入
function round(value)
    value = tonumber(value) or 0
    return math.floor(value + 0.5)
end


local qianLiangWei5BeiShu = ShiSheLiuRu(qianLiangWeiXiaoShu,qianLiangWeiXSX)
print(qianLiangWei5BeiShu)

local finial = qianLiangWei5BeiShu * ten * 10
print (finial)

--输出
digit:3
digit2:1
 ten:10
qianLiangWei:69
6-->0.9
7
700

整数最靠近5的倍数

代码语言:javascript
复制
function GetDengJiZhengByNear5(num)
    local geWei = num % 10
	local zhengPart,xiaoPart = math.modf(num/10)
	local xiaoShu = num/10
    if geWei <= 2 then
        return zhengPart *10
    elseif geWei >= 3 and geWei <= 7 then
        return zhengPart *10 + 5
    elseif geWei >= 8 then

        return round(xiaoShu) * 10
    end
end

--四舍五入
function round(value)
    value = tonumber(value) or 0
    return math.floor(value + 0.5)
end


num = 59
print(GetDengJiZhengByNear5(num))

输出
60
本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-08-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • math.modf
  • math.floor
  • 小数精度截取
  • 获取一个数的位数
  • 整数4舍6入,5保留
  • 整数最靠近5的倍数
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com