Skip to content Skip to sidebar Skip to footer

How To Compute The Number Of Bills / Coins When Making Change?

I want to compute the numbers of coins when making change. My problem with my code is, that it does not work for the last coins (1cent, 2cent), although I implemented them in my co

Solution 1:

The reason that it fails for the cents is that the remaining money becomes something like 0.0099999999856 instead of 0.01 because of floating point inaccuracies.

Here is your code converted to calculate with integer cents instead of decimals, thereby avoiding the floating point problems:

$(document).ready(function(){
  $(".calculate").bind("keyup change input paste", function(){

    var billsAndCoins = [50000, 20000, 10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1];
    var number = {};

    var money = Math.round($("#moneytochange").val() * 100);
    billsAndCoins.forEach(function(entry) {
      number[entry] = (money - money % entry)/ entry;
      $("#e" + entry).html(number[entry] + " * " + (entry/100));
      money = money % entry;
    });

  });
});
input {
	text-align: center;
	font-size: 3vw;
	margin: 017%;
	width: 60%;
	border: none;
	border-bottom: 4px solid #7C4DFF;
	outline: none;
	font-family: 'Raleway', sans-serif;
	padding: 1%3%1%3%;
	transition: border-radius 0.3s ease-out;
	opacity: 50%;
}
input:focus {
	border-radius: 1vw;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="number"class="calculate"id="moneytochange"placeholder="€"><pid="e50000">0 *</p><pid="e20000">0 *</p><pid="e10000">0 *</p><pid="e5000">0 *</p><pid="e2000">0 *</p><pid="e1000">0 *</p><pid="e500">0 *</p><pid="e200">0 *</p><pid="e100">0 *</p><pid="e50">0 *</p><pid="e20">0 *</p><pid="e10">0 *</p><pid="e5">0 *</p><pid="e2">0 *</p><pid="e1">0 *</p>

Solution 2:

I'll go as far as to blame JavaScript for rounding it automatically.

Considder using cents rather than entire euro, then devide it by 100 to get the euros.

I know from experience that some grocery stores also use cents rather than whole euros - It's a common thing that integers are prefered over decimals

$(document).ready(function(){
  $(".calculate").bind("keyup change input paste", function(){

    var billsAndCoins = [50000, 20000, 10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1];
    varnumber = {};

    var money = $("#moneytochange").val();
    $("#change").html("");
    var cents = money * 100;
    billsAndCoins.forEach(function(entry) {
        number[entry] = (cents - (cents % entry))/ entry;
        if(number[entry]>0) $("#change").append("<p>" + entry/100 + " * " + number[entry] + "</p>")
            cents = cents % entry;
      });
   });
});

http://jsfiddle.net/eLzfd6tt/2/

Post a Comment for "How To Compute The Number Of Bills / Coins When Making Change?"