Change Calculator

Joined
Jan 25, 2023
Messages
1
Reaction score
0
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
 
Joined
Mar 28, 2022
Messages
82
Reaction score
11
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:
Joined
Jul 3, 2022
Messages
93
Reaction score
23
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}
 

Ask a Question

Want to reply to this thread or ask your own question?

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.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top