Created
January 10, 2014 17:25
-
-
Save elclanrs/8358553 to your computer and use it in GitHub Desktop.
Working with money in JS using integers instead of floating point
This file contains 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
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