Saturday, 24 January 2015

How to check if value is a number (isNumer()) in javascript

After Stubbling at this challenge, i googled and found different solutions include the jQuery implementation of this, but none seems to do what i wanted, they either return true or false.
I wanted to know if a value is a number whether it's a typeof string or number. The codes below did the job very well, unlike !isNaN() or $.IsNumeric() which return true in the case of newline or space.
var isNumber = function(v){
    //return typeof v === 'number' && isFinite(v);
    return !isNaN(parseFloat(v)) && isFinite(v);
}
The commented code is the yahoo UI implementation which i tried but didn't give me what i wanted.
Return false if typeof is 'string' while true if typeof is 'number'. But the uncommented code does the job.

Than you for reading. Please post your comment.