-4

I am creating a program in which I have 3 available currencies, each one takes 100 of the previous to obtain. Using coins for example, I have 145 pennies. How can I convert that to 1 dollar, 45 pennies, or no ten dollar bills, 1 dollar, and 45 pennies? I have tried to convert the number to a string and use substr() functions determined by the number's length. So if a number was greater than 3 digits, I could not figure out how to take the substr of the 1st digit and last 2 while remaining consistent with all lengths.

adapap
  • 137
  • 1
  • 1
  • 5
  • can you post your code? – omarjmh May 18 '16 at 01:28
  • 3
    Substrings? Why not just use maths, specifically [integer division](http://stackoverflow.com/questions/4228356/integer-division-in-javascript) (and remainder). – Dan Mašek May 18 '16 at 01:36
  • 1
    I think if the title was changed then this question would be very applicable to many problems faced by new programmers, having said that, a first attempt would have been a good addition to the question –  May 18 '16 at 01:41

1 Answers1

3

You could use modulo, basically finding the remainders of dividing by 100, and 10,000 (100*100).

function returnCurrencies(baseCoins)
{
  //Number of bigCoins can be found by subtracting the remainder of % 10000 then dividing by 10000
  var bigCoins = (baseCoins - (baseCoins % 10000))/10000;
  //Now take off the bigCoins from the input
  baseCoins %= 10000;
  //Same for medCoins, but with 100
  var medCoins = (baseCoins - (baseCoins % 100))/100;
  //Now take off the medCoins from the input
  baseCoins %= 100;
  //Whatever is left is the small coins
  return [bigCoins, medCoins, baseCoins];
}

returnCurrencies(145); //[0, 1, 45]

EDIT

If the modulo thing was not clear, I'll try to explain in more detail:

var bigCoins = (baseCoins - (baseCoins % 10000))/10000;

This counts the number of big coins in a few steps:

  1. Find the number of coins that won't make big coins:

(baseCoins % 10000)

This returns the remainder of division, eg 15 % 4 == 3 which is how many coins won't make big coins, however we wan't however many will, so...

  1. Subtract them from the total:

baseCoins - (baseCoins % 10000)

Of course whatever is here will be divisible by 10,000, or a whole number of big coins, leading to the final step:

  1. Convert those base coins to big coins:

(baseCoins - (baseCoins % 10000))/10000

Because there are 10,000 baseCoins in a bigCoin.

  1. Then take all the bigCoins away from baseCoins:

baseCoins %= 10000

(This is just the remainder, you could also subtract bigCoins*10000 from baseCoins)

And of course the same applies to medCoins.

  • I like how your answer clearly spells out what you're doing and addresses your concern that the OP was from someone new to programming. – Ro Yo Mi May 18 '16 at 02:49