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.
Conversion syntax. 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).
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 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.
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)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.
Info 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");
}PARSEINT: NaN
ISNAN
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 13, 2023 (edit).