Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading