當前位置:編程學習大全網 - 源碼下載 - lua中精度計算

lua中精度計算

--1.使用string格式化

--保留2位小數,返回字符串類型

function strFormat(num)

return string.format("%.2f", num)

end

--2.數學計算,去除精度後的數字

--保留2位小數返回number類型

function numberFormat(num)

return math.floor(num * 100) / 100

end

--print(strFormat(1.13456))

--print(numberFormat(123.456789))

--延申使用

--@return number

--@param num 數字

--@param accurancy 精度 正整數

function accurancyFormat(num, accurancy)

if type(num) == "number" and type(accurancy) == "number" then

if accurancy % 1 == 0 and accurancy > 0 then

local num1 = math.pow(10, accurancy)

return math.floor(num * num1) / num1

else

error("請輸入類型為正整數的精度")

end

else

error("請輸入2個number類型")

end

end

--print(accurancyFormat(1.2, 2))

--取余求精度的局限性(部分版本會出現問題)

function accFormat(num, accurancy)

return num - num % math.pow(0.1, accurancy)

end

--由於(部分版本)lua中1%0.1 = 0.1 而並不是0,所以如果當前num的精度小於輸入的精度數時會出現問題

--print(1 % 0.1)

--print(accFormat(1, 1))

--正確版本的取余實現 a % b == a - ((a // b) * b)

--取余求精度的優化

function fmod(num1, num2)

return num1 - num1 // num2 * num2

end

function accFormatExtend(num, accurancy)

return fmod(num ,math.pow(0.1, accurancy))

end

--print(fmod(1, 0.1))

--print(1 % 0.1)

--print(accFormatExtend(1, 1))

  • 上一篇:盒子全景聲源代碼
  • 下一篇:佛山交通卡充值點?
  • copyright 2024編程學習大全網