parseInt ExamplesConvert strings to ints with the parseInt function. Use Number and parseFloat.
This page was last reviewed on Feb 28, 2023.
ParseInt. A program sometimes has a string but needs an int. For example in numerical operations, ints can be used but strings cannot be.
Conversion syntax. In JavaScript we can convert a string to an int with parseInt, a built-in method. Another option is with plus (to implicitly convert to an int).
First example. Here we have a string with 5 digits in it. To explore numeric conversions in JavaScript, we surround our parsing statements in a loop.
Part 1 We loop over the digits in our string with a for-loop and convert each one to a number.
Part 2 We use parseInt, a plus, and the Number constructor. Each string is converted in 3 different ways.
Part 3 We sum up all the numbers to show that they are valid digits and get the value 45.
var codes = "12345"; var sum = 0; // Part A: loop over chars and convert them to ints. for (var i = 0; i < codes.length; i++) { // Part B: apply numeric conversion. var test1 = parseInt(codes[i]); var test2 = +codes[i]; var test3 = Number(codes[i]); // Write our ints. console.log("INT: " + test1); console.log("INT: " + test2); console.log("INT: " + test3); // Sum the total. sum += test1 + test2 + test3; } // Write the sum. console.log("SUM: " + sum);
INT: 1 INT: 1 INT: 1 INT: 2 INT: 2 INT: 2 INT: 3 INT: 3 INT: 3 INT: 4 INT: 4 INT: 4 INT: 5 INT: 5 INT: 5 SUM: 45
ParseFloat. Suppose we have a number with a fractional part like 1.5. This is a floating-point number. We need to use the parseFloat method to retain the fractional part.
Here We use parseInt, which discards everything after the decimal place, and parseFloat.
var test = "100.534"; var resultInt = parseInt(test); console.log("PARSEINT: " + resultInt); var resultFloat = parseFloat(test); console.log("PARSEFLOAT: " + resultFloat)
IsNaN. Sometimes a string cannot be parsed. It may contain a word or other text. Here the parseInt method returns NaN, a special value in JavaScript.
Detail We can use the isNaN built-in method to test to see if nothing was parsed by parseInt.
// This string cannot be parsed. var test = "abc"; var result = parseInt(test); console.log("PARSEINT: " + result); // We can detect not a number with isNaN. if (isNaN(result)) { console.log("ISNAN"); }
A summary. When necessary, a plus sign provides fast string to int conversions in Chromium. Other modern browsers seem to have similar benefits here.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 28, 2023 (simplify).
© 2007-2023 Sam Allen.