Wednesday 29 August 2018

JavaScript: parseInt: Convert string to integer

parseInt(string, radix);
parseInt method takes a string and radix as arguments, and convert the string to integer in given radix.

var a = parseInt("0377", 8); // Return 255
var b = parseInt("255", 10); // Return 255
var c = parseInt("0xff", 16); // Return 255

parseInt converts the character by character, if it is unable to convert any character it ignores it and all succeeding characters, returns the integer value parsed up to that point.

var d = parseInt("123edf56", 10); // Return 123

If the first character cannot be converted to a number, parseInt returns NaN.

parseInt.html
<!DOCTYPE html>

<html>

<head>
    <title>parseInt</title>
</head>

<body>
    <script type="text/javascript">
        var a = parseInt("0377", 8); // Return 255
        var b = parseInt("255", 10); // Return 255
        var c = parseInt("0xff", 16); // Return 255

        var d = parseInt("123edf56", 10); // Return 123
        var e = parseInt("a1234", 10); // Return NaN

        var f = parseInt("11111111", 2); // Return 255

        document.write("a = " + a + "<br />");
        document.write("b = " + b + "<br />");
        document.write("c = " + c + "<br />");
        document.write("d = " + d + "<br />");
        document.write("e = " + e + "<br />");
        document.write("f = " + f + "<br />");
    </script>
</body>

</html>



Previous                                                 Next                                                 Home

No comments:

Post a Comment