Reputation: 31237
function compare() {
var value1 = parseInt(document.getElementById("box3").value);
var value2 = parseInt(document.getElementById("box4").value);
var display = document.getElementById("box5");
if (value1 === 0 || value2 === 0) {
display.value = "You have entered zero";
} else if (value1 == value2) {
display.value = "The numbers are the same";
} else if (value1 % value2 == 0) {
display.value = "The first is divisible by the second";
} else if (value2 % value1 == 0) {
display.value = "The second is divisible by the first";
} else {
display.value = "They are not divisible";
}
}
<p> Enter two numbers and we will tell you if they are evenly divisble</p>
<p> Enter your first number:</p> <input type="text" id="box3">
<p> Enter your second number: </p> <input type="text" id="box4">
<button id="compareValue" onclick="compare()">Compare Values</button>
<p> Output will appear here: </p> <input text="type" id="box5" disabled>
In the above code, enter 89.09 in the first number input and 0.05 into the second number input. Clicking on compare values returns
You have entered zero
The question is why?
Upvotes: 0
Views: 113
Reputation: 53198
Parsing 0.05
as an integer produces 0
:
The
parseInt()
function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
You're probably looking for parseFloat()
instead:
var value1 = parseFloat(document.getElementById("box3").value);
var value2 = parseFloat(document.getElementById("box4").value);
Alternatively, it may be better to cast it as a number using either Number()
or the +
prefix operator as @pointy has suggested below:
let value1 = Number(document.getElementById('box3').value);
Upvotes: 4