Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ferdelamad/a80ec5c78f83b597a553850266fc34d8 to your computer and use it in GitHub Desktop.
Save ferdelamad/a80ec5c78f83b597a553850266fc34d8 to your computer and use it in GitHub Desktop.
cashAmount
// Problem case with floating-point arithmetic: 0.10 + 0.20 !== 0.30
// But for us, should be: 0.10 + 0.20 === 0.30
function CashAmount (amount) {
this.amount = amount;
};
CashAmount.prototype.totalInPennies = function() {
const result = this.amount * 100;
return result;
};
CashAmount.prototype.addDoubleAmount = function(amount) {
this.amount += amount;
return this.amount;
};
CashAmount.prototype.quantityOfEachDenomination = function() {
var cents = this.amount.toString().split('.');
if (cents[1].length === 1) {
cents = Number(cents[1]) * 10;
} else {
cents = Number(cents[1]);
}
var denominations = {
'hundreds': Math.floor(this.amount / 100),
'fifties': Math.floor(this.amount / 50),
'twenties': Math.floor(this.amount / 20),
'tens': Math.floor(this.amount / 10),
'fives': Math.floor(this.amount / 5),
'ones': Math.floor(this.amount / 1),
'quarters': Math.floor(Math.floor(this.amount / 1) * 4) + Math.floor(cents / 4),
'dimes': Math.floor(Math.floor(this.amount / 1) * 10,
'nickels': Math.floor(Math.floor(this.amount / 1) * 20,
'pennies': Math.floor(Math.floor(this.amount / 1) * 100
};
return denominations;
};
CashAmount.prototype.toDouble = function() {
return this.amount;
};
CashAmount.prototype.toDouble = function() {
return this.amount.toString();
};
//EXAMPLE
/*
var cash = new CashAmount(10.50);
cash.totalInPennies(); // -> 1050
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment