Last Updated: February 25, 2016
·
36.81K
· teddy

JavaScript Try Parse int

JavaScript provides isNaN
, which returns a bool whether the value is an int or not. But this functionality can be wrapped into a handy function which will actually return a Number value of an object, given the specified radix. If the value is not an int, it will return a default value.

inputs are as follows:

val: the object to try to parse as an int

default_val: the value to return if this is not an int

radix: the base of the number to return (ex: 2 for binary, 10 for base10 which we are accustomed to counting in)

var int_try_parse = function(val, default_val, radix)
{
    try
    {
        radix = radix || 10;
        default_val = default_val || 0;

        //validate this object is not null
        if (val != null)
        {
                    //convert to string
            var that = JSON.stringify(val);
            if (that.length > 0)
            {
                //check to see the string is not NaN, if not parse
                if (!isNaN(that))   
                    return parseInt(that, radix);
            }
        }
    }
    catch (err)
    {
        console.log(err);   
    }
    //this is not a number
    return default_val;
}

some test cases:

Binary

int_try_parse(1010, 0, 2)
=>10


int_try_parse(10, 0, 2)
=>2

Base 10

int_try_parse(1010, 0, 10)
=>1010

int_try_parse(10, 0, 10)
=>10

invalid objects

int_try_parse([1010], 0, 10)
=>0

int_try_parse({val:1010}, 0, 10)
=>0

int_try_parse({val:1010}, -50, 10)
=>-50