Lua 重要数字

Lua significant figures

我正在尝试制作一个函数,将数字四舍五入到用户给出的特定数量的有效数字,例如,如果用户给我数字

234.235534 with 5 significant numbers, the function should return 234.24

我认为您正在寻找 [fs]?printf's %g 修饰符。

converts floating-point number to decimal or decimal exponent notation depending on the value and the precision.

其中,精度 定义为:

. followed by integer number or *, or neither that specifies precision of the conversion. In the case when * is used, the precision is specified by an additional argument of type int. If the value of this argument is negative, it is ignored. If neither a number nor * is used, the precision is taken as zero.

那么,你想要:

> return ("%.5g"):format(234.235534)
234.24
> return  ("%.6g"):format(x)
234.236

我不是一个程序员,但是在我对 lua 中推荐的其他舍入函数感到失望之后,我想出了这个供自己使用。这应该可以满足您的要求。

function sigFig(num,figures)
    local x=figures - math.ceil(math.log10(math.abs(num)))
    return(math.floor(num*10^x+0.5)/10^x)
end

现在,就有效数字而言,它不会向数字添加额外的零来表示精度。例如:

sigFig(234.235534,5) 将产生 234.24

sigFig(234.0000001,6) 将产生 234.0,而不是 234.000