# Change Calculator

#### choudhmh

Hello;
I'm trying to write this function where whatever the amount it should give change in coin accordingly and result sent as an object. Finding it a but tricky - any support on how the code should be written

function changeCalculator (num) {
var res = {};

for (var i = 0; i < num.length; i++) {
}
return res;
};

result should be in this format:
changeCalculator(13);
// should return
{'10':1,'2':1,'1':1}

Any help in writing the function will be appreciated. Thanks

We still don't know the given types of coins

#### AngleWyrm

Could do something like this:
Java:
``````  class Change{
public int quarters = 0;
public int dimes    = 0;
public int nickels  = 0;
public int pennies  = 0;

public Change(float total){
calculate_change(total);
}

public Change calculate_change(float total){
// calculate how many of each coin here
return this;
}

public String ToString(){
return String.format("{ '25':%s, '10':%s, '5':%s, '1':%s }",
quarters, dimes, nickels, pennies;
}
}``````

Last edited:

JavaScript:
``````function changeCalculator(num){
let res = {};
[25, 10, 5, 1].forEach( x => num >= x ? (i = Math.floor(num / x), num -= x * i, res[`'\${x}'`] = i) : null );
return res;
}

console.log( changeCalculator(13) ); // {'10': 1, '1': 3}
console.log('==============');
console.log( changeCalculator(93) ); // {'25': 3, '10': 1, '5': 1, '1': 3}
console.log('==============');
console.log( changeCalculator(55) ); // {'25': 2, '5': 1}``````

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.