ParseInt
A Node.js program sometimes has a string
but needs an int
. For example in numerical operations, ints can be used but strings cannot be.
In Node 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
).
Here we have a string
with 5 digits in it. To explore numeric conversions in JavaScript, we surround our parsing statements in a loop.
string
with a for
-loop and convert each one to a number.parseInt
, a plus, and the Number constructor. Each string
is converted in 3 different ways.var codes = "12345"; var sum = 0; // Part 1: loop over chars and convert them to ints. for (var i = 0; i < codes.length; i++) { // Part 2: 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); // Part 3: 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.
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)PARSEINT: 100 PARSEFLOAT: 100.534
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.
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"); }PARSEINT: NaN ISNAN
When necessary, a plus sign provides fast string
to int
conversions in Node.js. But the parseInt
or Number constructs are usually a better choice.