How to convert a string to an integer in JavaScript?

To convert a string to an integer in JavaScript, use one of the following methods depending on your needs:

1. parseInt() (Most Common)

Parses a string and returns an integer. Always specify the radix (base) to avoid unexpected behavior (e.g., parseInt("08") treats “08” as octal without 10 as the radix).

const str = "123";
const num = parseInt(str, 10); // 123 (base 10)

Edge Cases:

  • Truncates decimals: parseInt("123.99", 10) → 123
  • Non-numeric characters: parseInt("123abc", 10) → 123 (ignores trailing non-digits)
  • Invalid strings: parseInt("abc", 10) → NaN

2. Unary Plus Operator

Converts a string to a number (integer or float). Use Math.trunc() or Math.floor() to force an integer.

const str = "456";
const num = +str; // 456 (number type)

Edge Cases:

  • Decimals: +"123.45" → 123.45 (float)
  • Invalid strings: +"12px" → NaN
  • Empty/whitespace: +" " → 0 (⚠️ caution: Number(" ") also returns 0!)

3. Number()

Explicitly converts a string to a number (similar to the unary +).

const str = "789";
const num = Number(str); // 789

Edge Cases:

  • Decimals: Number("123.99") → 123.99
  • Invalid strings: Number("123abc") → NaN

4. Bitwise Operators (Truncate to 32-bit Integer)

Bitwise operations like | 0 truncate decimals and convert to a 32-bit integer.

const str = "123.99";
const num = str | 0; // 123 (truncates decimals)

Limitations:

  • Only works for numbers within 32-bit range (-2^31 to 2^31-1).
  • "2147483648" | 0 → -2147483648 (overflow).

5. Math.floor() or Math.trunc()

Use with parseFloat() to handle decimals:

const str = "123.99";
const num = Math.floor(parseFloat(str)); // 123
// or
const num = Math.trunc(Number(str)); // 123 (removes decimals)

Method Comparison

MethodExample InputOutputNotes
parseInt(str, 10)"123.45"123Truncates decimals
Number(str)"123.45"123.45Returns float if decimals exist
+str"123"123Short syntax, same as Number()
str | 0"123.99"12332-bit integer, truncates decimals
Math.trunc(+str)"-456.7"-456Removes decimals (no rounding)

Handling Edge Cases

  1. Empty/Whitespace Strings:
   const str = "   ";
   console.log(parseInt(str, 10)); // NaN
   console.log(Number(str));       // 0 (⚠️)
   console.log(+str);              // 0 (⚠️)
  1. Non-Numeric Characters:
   const str = "abc123";
   console.log(parseInt(str, 10)); // NaN
   console.log(Number(str));       // NaN
  1. Hexadecimal/Binary Strings:
   console.log(parseInt("0xFF", 16)); // 255 (specify radix for non-decimal)

Best Practices

  • Use parseInt(str, 10) for explicit integer parsing (avoids octal/hex issues).
  • Use Number() or + if the string is guaranteed to be a valid number.
  • Validate inputs first for non-numeric characters:
  function safeParseInt(str) {
    if (!/^-?\d+$/.test(str)) return NaN; // Check for valid integer string
    return parseInt(str, 10);
  }

Example Workflow

const userInput = "42px";
const num = parseInt(userInput, 10); // 42 (ignores "px")

if (!isNaN(num)) {
  console.log("Valid integer:", num);
} else {
  console.log("Invalid input");
}

Choose the method that best fits your use case and validate inputs to avoid surprises!

Leave a Reply

Your email address will not be published. Required fields are marked *