Skip to content

Instantly share code, notes, and snippets.

@apssouza22
Forked from elclanrs/money.js
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apssouza22/cef1921a10ce47e95afe to your computer and use it in GitHub Desktop.
Save apssouza22/cef1921a10ce47e95afe to your computer and use it in GitHub Desktop.
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]);
if(typeof parts[1] != 'undefined'){
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