Skip to content

Instantly share code, notes, and snippets.

@brundage
Created May 18, 2012 13:28
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brundage/2725275 to your computer and use it in GitHub Desktop.
Save brundage/2725275 to your computer and use it in GitHub Desktop.
Problematic Decimal Arithmetic in Javascript
// decimal_arithmetic.js
// From http://www.brewsession.com/problematic-decimal-arithmetic-in-javascript/
String.prototype.digitsAfterDecimal = function()
{ var parts = this.split(".", 2); // FIXME: Not international!
if( ! parts[1] )
{ parts[1] = ""; }
return parts[1].length;
};
Number.prototype.biggerScalar = function(n)
{ return n.scale() > this.scale() ? n.scale() : this.scale(); };
Number.prototype.digitsAfterDecimal = function()
{ return this.toString().digitsAfterDecimal(); };
Number.prototype.divided = function(n)
{ return this.dividedBy(n); };
Number.prototype.dividedBy = function(n)
{ return this.multiply( n.reciprocal() ); };
Number.prototype.minus = function(n)
{ return this.plus( n.negative() ); };
Number.prototype.multiply = function(n)
{ var s = this.biggerScalar(n);
return (Math.round(s*this,0) * Math.round(s*n,0)) / (s*s);
};
Number.prototype.negative = function()
{ return -1 * this; };
Number.prototype.plus = function(n)
{ var s = this.biggerScalar(n);
return (Math.round(s*this,0) + Math.round(s*n,0)) / s;
};
Number.prototype.reciprocal = function()
{ return 1 / this; };
Number.prototype.scale = function()
{ return Math.pow(10, this.digitsAfterDecimal() ); };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment