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

Javascript math not displaying right output

I want the program to increase the number of notes when the user enters a number higher than 5 if the user enters 12 then its should say that you have 2 notes. I would also my to know if my code could be made more readable and more efficient

const box = document.getElementById('box');
const store = document.getElementById('store');

function notesChecker() {
  let num = parseInt(box.value);

  if (num / 5 == 0) {
    store.textContent = 'You go this number of notes ' + num;
  } else {
    store.textContent = 'You dont have enough money for notes';
  }
}
body {
  text-align: center;
}
<h1>Number of notes</h1>
<p>Enter a number and it will tell you the number of notes you will get in £5 notes.</p>
<input id="box" type="number">
<button onclick="notesChecker()">Submit</button>
<div id="store"></div>

>Solution :

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

It looks like you expected the / operator to perform an integer division, but that is not the case. For example 3 / 5 is 0.6, not 0.

Secondly, you don’t want to display the input number in the output message, but the number of notes, for which you need to use the integer division by 5.

Finally, if that quotient is 0, then you should display the other message ("you don’t have enough…"), so you need to either swap the messages or invert the if condition.

You can use Math.floor to achieve what you want:

const box = document.getElementById('box');
const store = document.getElementById('store');

function notesChecker() {
  let num = parseInt(box.value);
  let notes = Math.floor(num / 5);
  if (notes > 0) {
    store.textContent = "You got this number of notes " + notes;
  } else {
    store.textContent = "You don't have enough money for notes";
  }
}
body {
  text-align: center;
}
<h1>Number of notes</h1>
<p>Enter a number and it will tell you the number of notes you will get in £5 notes.</p>
<input id="box" type="number">
<button onclick="notesChecker()">Submit</button>
<div id="store"></div>
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