Search code examples
javascriptinputmaxalertnegative-number

Calculate the maximum number of the three in javascript


This is my code, and it works, but only with positive numbers. If I write nothing into the input it considers as value 0, and this is a problem if I have only one or two negative numbers.

function Calculeaza() {
    var a = document.getElementById('input1').value;
    var b = document.getElementById('input2').value;
    var c = document.getElementById('input3').value;
    var max = 0;

    var max = Math.max(a, b, c);

    if (a == '' && b == '' && c == '') {
        max = 'Input at least one number';
    }
    alert(max);
}

I tried to take as input only one negative number, and I expect to alert that as the maximum, but in the Alert I get 0 as an answer.


Solution

  • The reason why you are getting 0 as the maximum value when you enter a negative number is that Math.max() function considers an empty string or any non-numeric input as 0. To handle negative numbers properly, you can modify your code to check if the input values are valid numbers using isNaN() function before calculating the maximum value.

    Here's an updated code snippet that checks for valid input values and considers negative numbers as the maximum value:

      var a = parseFloat(document.getElementById("input1").value);
      var b = parseFloat(document.getElementById("input2").value);
      var c = parseFloat(document.getElementById("input3").value);
      var max = -Infinity;
    
      if (isNaN(a) && isNaN(b) && isNaN(c)) {
        max = "Input at least one number";
      } else {
        if (!isNaN(a) && a > max) {
          max = a;
        }
        if (!isNaN(b) && b > max) {
          max = b;
        }
        if (!isNaN(c) && c > max) {
          max = c;
        }
      }
      
      alert(max);
    }