commit 9b6ef07fc1867b47fbeb55356486e55bb12c98ab
Author: Nihal Jere <nihal@nihaljere.xyz>
Date: Tue, 16 Aug 2022 22:57:16 -0500
add decmath
Diffstat:
1 file changed, 35 insertions(+), 0 deletions(-)
diff --git a/decmath.lua b/decmath.lua
@@ -0,0 +1,35 @@
+-- decimal arithmetic using limath
+
+local imath = require "imath"
+
+local meta = {
+ __tostring = function(val)
+ local str = tostring(val.sig)
+ return string.sub(str, 1, #str + val.exp) .. "." .. string.sub(str, #str + val.exp + 1, #str)
+ end,
+ __add = function(a, b)
+ if a.exp < b.exp then
+ a, b = b, a
+ end
+
+ if a.exp > b.exp then
+ return {sig = b.sig * 10^(b.exp - a.exp), exp = a.exp}
+ end
+
+ return {sig = a.sig + b.sig, exp = a.exp}
+ end
+}
+
+return {
+ new = function (val)
+ if type(val) == "string" then
+ -- todo normalize
+ local asint, count = string.gsub(val, "%.", "")
+ local pos = string.find(val, "%.")
+ assert(count == 1)
+ local dec = {sig=imath.new(asint), exp=pos-#val}
+ setmetatable(dec, meta)
+ return dec
+ end
+ end
+}