I'm learning JavaScript and I have a page that displays the result of dividing two user-inputted numbers.
I didn't like that (1 / 3) would fill the whole result box with 3.333333333333..., so I set the result with .toFixed(4). But this has the result of making (4 / 2) return 2.0000 instead of just 2.
So, in order to fix that I check if (answer % 1 == 0), in which case it displays the answer normally, then checks (answer % 0.1 == 0), which displays answer.toFixed(1), and so on, with the final else being .toFixed(4).
This works as intended for some numbers but not for others, and I don't see why or what's going wrong in the cases it doesn't work.
Examples:
(2 / 5)returns0.4. This satisfies the second condition,(answer % 0.1 == 0), and returnsanswer.toFixed(1), displaying0.4. Great.(2 / 10)also works and displays0.2, and something like(2 / 7)correctly gets pushed to theelseand displays0.2857.(2 / 8)returns0.25, then incorrectly displays0.2500(2 / 20)correctly returns and displays0.1(9 / 6)returns1.5, then incorrectly displays1.5000(2 / 4)returns0.5, but displays0.5000. It failed all the conditions and jumps to theelsesentence, soanswer.toFixed(4)is used.
Why does JavaScript consider (0.4 % 0.1 == 0) to be true, but (0.5 % 0.1 == 0) to be false?
This is my current code:
let num1 = parseFloat($("calcInput1").value);
let num2 = parseFloat($("calcInput2").value);
answer = num1 / num2;
if (answer % 1 == 0) {
document.getElementById("calcResult").value = answer;
alert("answer % 1 == 0");
} else if (answer % 0.1 == 0) {
document.getElementById("calcResult").value = answer.toFixed(1);
alert("answer % 0.1 == 0");
} else if (answer % 0.01 == 0) {
document.getElementById("calcResult").value = answer.toFixed(2);
alert("answer % 0.01 == 0");
} else if (answer % 0.001 == 0) {
document.getElementById("calcResult").value = answer.toFixed(3);
alert("else");
} else {
document.getElementById("calcResult").value = answer.toFixed(4);
}