user3369726
user3369726

Reputation: 35

parseInt()/parseFloat() to ignore non-numeric arguments

How can I get non-numeric arguments to be ignored with parseInt or parseFloat in the following function?

 function highestNumber(num1, num2, num3) {
      var highest = Math.max(num1, num2, num3);
      return highest;
 }

 alert(highestNumber(26,1,109));

Upvotes: 0

Views: 1171

Answers (1)

Felix Kling
Felix Kling

Reputation: 816790

I don't think parseInt or parseFloat are of any use here. You can simply test whether a value is a number and filter out all non-number values:

return Math.max.apply(Math, Array.prototype.filter.call(arguments, function(value) {
    return typeof value === 'number';
}));

arguments is an array-like object which contains all arguments passed to the function. But since it isn't an actual array, we have to use Array.prototype.<method>.call to use an array method on it.

.apply lets you call a function with an unknown number of parameters by just passing an array as second argument.


If you want to allow numeric strings, e.g. "123", you can use isNaN instead (and some extra guards against null and empty string):

return Math.max.apply(Math, Array.prototype.filter.call(arguments, function(value) {
    return value != null && value !== "" && !isNaN(value);
}));

Why extra tests for null and ""? Because Number("") and Number(null) return 0, so isNaN will return false for both (but we still want to exclude those values).

Upvotes: 2

Related Questions