Last active
August 29, 2015 14:06
-
-
Save panda01/a80bc33300399e8b70b5 to your computer and use it in GitHub Desktop.
Allows for floating point math to be done in js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Num(v, precision) { | |
this.val = v; | |
var multiplier = Math.pow(10, precision || 3), | |
// Helper fn, Makes a new num for chaining | |
m = function(n) { | |
return new Num(n, Math.log10(multiplier)); | |
} | |
// pseduo operand overriding to allow for generic addition of nums | |
this.valueOf = function() { | |
return this.val * multiplier; | |
} | |
// Just in case | |
this.getMultiplier = function() { | |
return multiplier; | |
} | |
// All of the underscored methods return regular numbers | |
this._add = function(num) { | |
return (this.valueOf() + num) / multiplier; | |
} | |
this._subtract = function(num) { | |
return this.add(num*-1); | |
} | |
this._multiply = function(num) { | |
return (this.valueOf() * num) / (multiplier*multiplier); | |
} | |
this._divide = function(num) { | |
return (this.valueOf() / num); | |
} | |
// These return Num objects | |
this.add = function(num) { return m(this._add(num)); } | |
this.subtract = function(num) { return m(this._subtract(num)); } | |
this.multiply = function(num) { return m(this._multiply(num)); } | |
this.divide = function(num) { return m(this._divide(num)); } | |
return this; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment