Skip to content

Instantly share code, notes, and snippets.

@elclanrs
Created January 10, 2014 17:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save elclanrs/8358553 to your computer and use it in GitHub Desktop.
Save elclanrs/8358553 to your computer and use it in GitHub Desktop.
Working with money in JS using integers instead of floating point
var Money = (function(){
function Money(qty) {
this.whole = 0;
this.cents = 0;
this.add(qty);
}
Money.prototype.calc = function() {
while (this.cents > 100) {
this.cents -= 100;
this.whole += 1;
}
return this;
};
Money.prototype.add = function(qty) {
var parts = qty.split('.');
this.whole += Number(parts[0]);
this.cents += Number(parts[1]);
return this.calc();
};
Money.prototype.toString = function() {
return this.whole +'.'+ this.cents;
};
return Money;
}());
var m = new Money('90.75').add('50.43');
console.log(m); //=> {whole: 141, cents: 18}
console.log(m.toString()); //=> "141.18"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment