Search code examples
javascriptfunction

A Very SMALL function that have a BIG calculation Error


I'm trying to run this calculating function, and it's works fine for the most part, until it shows the result of the calculation.

For example, here it should output $1 as change, but it outputs $0, and no matter how much price variation output it takes, the change is always $0.

Could someone illuminate me please?

function dealCalc(pricePerUnity) {

    let userBudget = prompt("What's Your Budget?");
    let possibleAmount = userBudget / pricePerUnity ;
    let changeReturn = userBudget - ( possibleAmount * pricePerUnity );

    return alert("With that amount you can buy " + Math.floor(possibleAmount) + " Units \nand $" + changeReturn + " will be the Change!" );

}

dealCalc(3);


Solution

  • You're basically evaluating the arithmetic expression a - a/b * b (where a is userbudget and b is pricePerUnity). That is always going to equal 0, because a / b * b always equals a, and a - a is 0.

    You probably meant to force possibleAmount to be an integer:

    let possibleAmount = Math.floor(userbudget / pricePerUnity)