How can I convert a string to an integer in JavaScript?

Learn how can i convert a string to an integer in javascript? with practical examples, diagrams, and best practices. Covers javascript, string, integer development techniques with visual explanations.

Mastering String to Integer Conversion in JavaScript

Hero image for How can I convert a string to an integer in JavaScript?

Learn the various methods to convert strings to integers in JavaScript, understand their nuances, and choose the best approach for your use case.

Converting a string to an integer is a common task in JavaScript development. Whether you're parsing user input, processing data from an API, or performing calculations, understanding the different methods and their behaviors is crucial. This article will guide you through the most popular and effective ways to achieve this conversion, highlighting their strengths and potential pitfalls.

The Unary Plus Operator (+)

The unary plus operator + is a concise and often overlooked method for converting a string to a number. When placed before a string, it attempts to convert the string into its numerical representation. If the string contains non-numeric characters (other than leading/trailing whitespace or a single decimal point), it will result in NaN (Not-a-Number).

const str1 = "123";
const num1 = +str1; // num1 is 123 (number)

const str2 = "  456  ";
const num2 = +str2; // num2 is 456 (number)

const str3 = "123.45";
const num3 = +str3; // num3 is 123.45 (number)

const str4 = "abc";
const num4 = +str4; // num4 is NaN

const str5 = "123px";
const num5 = +str5; // num5 is NaN

Using the unary plus operator for string to number conversion.

Using parseInt() for Integer Conversion

The parseInt() function is specifically designed to parse a string argument and return an integer. It parses the string from left to right, stopping at the first non-numeric character. This makes it useful for extracting numerical prefixes from strings that might contain units or other text. It also accepts an optional radix argument, which specifies the base of the number (e.g., base 10 for decimal, base 16 for hexadecimal).

const str1 = "123";
const num1 = parseInt(str1); // num1 is 123

const str2 = "123.45";
const num2 = parseInt(str2); // num2 is 123 (truncates decimal part)

const str3 = "123px";
const num3 = parseInt(str3); // num3 is 123 (stops at 'p')

const str4 = "  -45  ";
const num4 = parseInt(str4); // num4 is -45

const str5 = "0xFF";
const num5 = parseInt(str5); // num5 is 255 (interprets as hexadecimal)

const str6 = "0xFF", 16;
const num6 = parseInt(str6, 16); // num6 is 255 (explicitly base 16)

const str7 = "abc";
const num7 = parseInt(str7); // num7 is NaN

Examples of parseInt() with and without radix.

flowchart TD
    A[Input String] --> B{Contains non-numeric chars?}
    B -- Yes, at start --> C[Result: NaN]
    B -- Yes, in middle/end --> D["Parse until first non-numeric (parseInt)"]
    B -- No --> E["Convert to Number (Unary Plus, Number())"]
    D --> F{Radix specified?}
    F -- Yes --> G[Parse with specified base]
    F -- No --> H[Default to base 10 (or 8/16 for '0x'/'0')]
    E --> I[Result: Number]
    G --> I
    H --> I

Decision flow for string to integer conversion methods.

The Number() Constructor

The Number() constructor, when used as a function (without new), can also convert a string to a number. Similar to the unary plus operator, it's stricter than parseInt(). If the string cannot be entirely converted into a valid number, Number() will return NaN. It handles floating-point numbers correctly.

const str1 = "123";
const num1 = Number(str1); // num1 is 123

const str2 = "  456  ";
const num2 = Number(str2); // num2 is 456

const str3 = "123.45";
const num3 = Number(str3); // num3 is 123.45

const str4 = "abc";
const num4 = Number(str4); // num4 is NaN

const str5 = "123px";
const num5 = Number(str5); // num5 is NaN

Using the Number() constructor for conversion.

Bitwise Operators for Integer Truncation

While not a direct conversion method, bitwise operators like the bitwise OR | 0 can be used to quickly truncate a floating-point number to an integer. This works because bitwise operations implicitly convert their operands to 32-bit signed integers. This method is very fast but should be used with caution as it only works for numbers within the 32-bit integer range and can produce unexpected results with very large numbers or NaN.

const floatStr = "123.789";
const int1 = +floatStr | 0; // int1 is 123

const negFloatStr = "-45.123";
const int2 = +negFloatStr | 0; // int2 is -45

const largeNumStr = "2147483647"; // Max 32-bit signed int
const int3 = +largeNumStr | 0; // int3 is 2147483647

const tooLargeNumStr = "2147483648"; // Exceeds 32-bit signed int
const int4 = +tooLargeNumStr | 0; // int4 is -2147483648 (overflows)

const nanStr = "abc";
const int5 = +nanStr | 0; // int5 is 0 (NaN becomes 0 in bitwise ops)

Using bitwise OR | 0 for integer truncation.