diff options
author | P. J. McDermott <pj@pehjota.net> | 2017-01-06 21:40:11 (EST) |
---|---|---|
committer | P. J. McDermott <pj@pehjota.net> | 2017-01-06 21:40:11 (EST) |
commit | d33281db4a6e1947863a61e9b15a0a87462197c9 (patch) | |
tree | 3987a0d2c629c760729e87401ccc8068b706d342 /lib | |
parent | fac6e17915e8631df5d4ab7f952333f6ee6b5fd6 (diff) | |
download | decmath.js-d33281db4a6e1947863a61e9b15a0a87462197c9.zip decmath.js-d33281db4a6e1947863a61e9b15a0a87462197c9.tar.gz decmath.js-d33281db4a6e1947863a61e9b15a0a87462197c9.tar.bz2 |
dadd(), dmul(): Implement
Diffstat (limited to 'lib')
-rw-r--r-- | lib/decmath.js | 51 |
1 files changed, 47 insertions, 4 deletions
diff --git a/lib/decmath.js b/lib/decmath.js index d32cf1d..fbb4e9e 100644 --- a/lib/decmath.js +++ b/lib/decmath.js @@ -33,14 +33,57 @@ function dadd(a, b) { - /* TODO: Implement */ - return a + b; + //console.log(a + " + " + b); + a = a.toString().split(".", 2); + b = b.toString().split(".", 2); + if (typeof a[1] == "undefined") a[1] = ""; + if (typeof b[1] == "undefined") b[1] = ""; + //console.log("ai: " + a[0] + ", af: " + a[1]); + //console.log("bi: " + b[0] + ", bf: " + b[1]); + var ce; + if (a[1].length == b[1].length) { + ce = a[1].length; + } else if (a[1].length < b[1].length) { + //console.log("padding af with " + (b[1].length - a[1].length) + + // " zeroes"); + a[1] += Array(b[1].length - a[1].length + 1).join("0"); + ce = b[1].length; + } else { + //console.log("padding bf with " + (a[1].length - b[1].length) + + // " zeroes"); + b[1] += Array(a[1].length - b[1].length + 1).join("0"); + ce = a[1].length; + } + //console.log("after padding:"); + //console.log("ai: " + a[0] + ", af: " + a[1]); + //console.log("bi: " + b[0] + ", bf: " + b[1]); + var as = a[0] + a[1]; + var bs = b[0] + b[1]; + //console.log("as: " + as + ", ae: " + a[1].length); + //console.log("bs: " + bs + ", be: " + b[1].length); + var cs = (parseInt(as, 10) + parseInt(bs, 10)).toString(); + //console.log("cs: " + cs + ", ce: " + ce); + //console.log(ce); + //console.log(cs.length); + //console.log(ce - cs.length + 1); + var pad = ce - cs.length; + if (pad > 0) cs = (Array(pad + 1).join("0") + cs).toString(); + return cs.substr(0, cs.length - ce) + "." + cs.substr(cs.length - ce); } function dmul(a, b) { - /* TODO: Implement */ - return a * b; + a = a.toString().split(".", 2); + b = b.toString().split(".", 2); + if (typeof a[1] == "undefined") a[1] = ""; + if (typeof b[1] == "undefined") b[1] = ""; + var as = a[0] + a[1]; + var bs = b[0] + b[1]; + var cs = (parseInt(as, 10) * parseInt(bs, 10)).toString(); + var ce = a[1].length + b[1].length; + var pad = ce - cs.length; + if (pad > 0) cs = (Array(pad + 1).join("0") + cs).toString(); + return cs.substr(0, cs.length - ce) + "." + cs.substr(cs.length - ce); } function drhtz(a, p) |