如何四舍五入到最接近的十分之一?
How to Round to the Nearest Tenth?
例如,给定任何 78.689 或 1.12 类型的数字,我正在寻找的是以编程方式将数字四舍五入到小数点后最接近的第十位。
我正在尝试在一个 math.floor()
函数四舍五入到最小整数的环境中执行此操作,据我从文档中可以看出,没有什么比 PHP的 round()
函数。
这里有一个简单的片段:http://lua-users.org/wiki/SimpleRound
function round(num, numDecimalPlaces)
local mult = 10^(numDecimalPlaces or 0)
return math.floor(num * mult + 0.5) / mult
end
当 numDecimalPlaces 为负数时,它会出现错误,但该页面上有更多示例。
在我的例子中,我只是想用字符串表示这个数字...但是,我想这个解决方案也可能对其他人有用。
string.sub(tostring(percent * 100), 1, 4)
因此,要将其恢复为数字表示,您只需对结果数字调用 tonumber()
。
你可以使用强制来做到这一点...
它像 printf 一样工作...您可以尝试执行类似此代码段中的操作。
value = 8.9756354
print(string.format("%2.1f", value))
-- output: 9.0
考虑到这是 roblox,将其设为全局变量会更容易,而不是制作单个模块或创建自己的 gloo。
_G.round = function(x, factor)
local factor = (factor) and (10 ^ factor) or 0
return math.floor((x + 0.5) * factor) / factor
end
例如,给定任何 78.689 或 1.12 类型的数字,我正在寻找的是以编程方式将数字四舍五入到小数点后最接近的第十位。
我正在尝试在一个 math.floor()
函数四舍五入到最小整数的环境中执行此操作,据我从文档中可以看出,没有什么比 PHP的 round()
函数。
这里有一个简单的片段:http://lua-users.org/wiki/SimpleRound
function round(num, numDecimalPlaces)
local mult = 10^(numDecimalPlaces or 0)
return math.floor(num * mult + 0.5) / mult
end
当 numDecimalPlaces 为负数时,它会出现错误,但该页面上有更多示例。
在我的例子中,我只是想用字符串表示这个数字...但是,我想这个解决方案也可能对其他人有用。
string.sub(tostring(percent * 100), 1, 4)
因此,要将其恢复为数字表示,您只需对结果数字调用 tonumber()
。
你可以使用强制来做到这一点... 它像 printf 一样工作...您可以尝试执行类似此代码段中的操作。
value = 8.9756354
print(string.format("%2.1f", value))
-- output: 9.0
考虑到这是 roblox,将其设为全局变量会更容易,而不是制作单个模块或创建自己的 gloo。
_G.round = function(x, factor)
local factor = (factor) and (10 ^ factor) or 0
return math.floor((x + 0.5) * factor) / factor
end