DEV Community

Cover image for JavaScript String to Int: Convert Strings to Integers
Mateen Kiani
Mateen Kiani

Posted on • Originally published at milddev.com

JavaScript String to Int: Convert Strings to Integers

JavaScript often surprises developers with how it handles types. Converting a string into a number seems straightforward, yet nuances hide in plain sight. One often overlooked aspect is how different conversion methods handle whitespace, prefixes, or invalid characters. Ever wondered why parseInt("08") sometimes returns NaN or how to choose between Number() and the unary plus operator?

The truth is, picking the right string-to-integer method can save hours of debugging. By understanding quirks like automatic radix detection, silent failures, or performance differences, you’ll write code that’s predictable and fast. Let’s dive in and explore these techniques so you can handle any string-to-int conversion with confidence.

parseInt Essentials

The built-in parseInt() function parses a string and returns an integer of the specified radix (base). Its signature is:

parseInt(string, [radix]);
Enter fullscreen mode Exit fullscreen mode

Key points:

  • Always pass a radix. Without it, leading zeros or 0x prefixes can change behavior:
    • parseInt("08")0 (in older engines) or NaN
    • parseInt("0x10")16
  • It stops reading at the first non-digit character:
  parseInt("123abc") // 123
  parseInt("abc123") // NaN
Enter fullscreen mode Exit fullscreen mode
  • It ignores leading whitespace:
  parseInt("   42") // 42
Enter fullscreen mode Exit fullscreen mode

Tips for safe usage:

Always specify the second argument to avoid ambiguous results.

Example:

const str = "1010";
const num = parseInt(str, 2); // 10 in decimal
Enter fullscreen mode Exit fullscreen mode

Number Function

The Number() constructor converts values to numbers, including strings. Its behavior differs from parseInt():

Number(value);
Enter fullscreen mode Exit fullscreen mode

Features:

  • Converts the entire string or returns NaN on failure:
  Number("123")    // 123
  Number("123abc") // NaN
Enter fullscreen mode Exit fullscreen mode
  • Handles floats and scientific notation:
  Number("3.14")   // 3.14
  Number("1e3")    // 1000
Enter fullscreen mode Exit fullscreen mode
  • Trims whitespace automatically:
  Number("  56 ")  // 56
Enter fullscreen mode Exit fullscreen mode

When to use:

  • You need strict conversion: no partial reads.
  • You expect floats or exponential formats.

Use Number() when you want an all-or-nothing conversion without partial success.

Unary Plus Operator

A terse way to convert strings to numbers is the unary plus:

+string;
Enter fullscreen mode Exit fullscreen mode

How it works:

  • Equivalent to Number(string) under the hood.
  • Very concise, but can hurt readability for some teams.

Examples:

+"123"    // 123
+"12.34"  // 12.34
+"1e2"    // 100
+"abc"    // NaN
Enter fullscreen mode Exit fullscreen mode

Pros and cons:

  • Pro: Shortest syntax.
  • Con: Might confuse readers unfamiliar with the operator.

The unary plus is great for quick scripts or pipelines where brevity matters.

Handling Edge Cases

Even the best methods can stumble on odd inputs. Watch out for:

  1. Empty strings:
   parseInt("") // NaN
   Number("")   // 0
   +""          // 0
Enter fullscreen mode Exit fullscreen mode
  1. Leading zeros:
   parseInt("08") // NaN without radix
Enter fullscreen mode Exit fullscreen mode
  1. Non-numeric suffixes or prefixes:
   parseInt("123px") // 123
   Number("123px")   // NaN
Enter fullscreen mode Exit fullscreen mode
  1. Negative numbers:
   parseInt("-10") // -10
   Number("-10")   // -10
Enter fullscreen mode Exit fullscreen mode
  1. Semicolon insertion traps such as:
   return
   +"123"; // Automatic semicolon; returns undefined
Enter fullscreen mode Exit fullscreen mode

Read more on does JavaScript need semicolons.

Whenever you face odd inputs, write small tests to see how your chosen method reacts.

Working with JSON Data

When dealing with API responses or stored data, you often parse JSON:

const json = '{"age": "30"}';
const obj = JSON.parse(json);
Enter fullscreen mode Exit fullscreen mode

Once parsed, the property obj.age is still a string. Convert it:

obj.age = parseInt(obj.age, 10);
// or
obj.age = +obj.age;
Enter fullscreen mode Exit fullscreen mode

Working with nested data:

function normalizeUser(user) {
  return {
    ...user,
    id: Number(user.id),
    score: parseInt(user.score, 10),
  };
}
Enter fullscreen mode Exit fullscreen mode

Learn more about JSON in what is JavaScript Object Notation (JSON).

Performance Tips

If you run conversions in tight loops or high-frequency code, measure impact:

  • Generally, unary plus is fastest.
  • Number() is close behind.
  • parseInt() can be slower due to parsing logic.

Benchmark example:

console.time('plus');
for (let i=0; i<1e6; i++) { +"123"; }
console.timeEnd('plus');

console.time('num');
for (let i=0; i<1e6; i++) { Number("123"); }
console.timeEnd('num');

console.time('parse');
for (let i=0; i<1e6; i++) { parseInt("123", 10); }
console.timeEnd('parse');
Enter fullscreen mode Exit fullscreen mode

Practical tips:

  • Cache conversions outside loops where possible.
  • Use typed arrays or WebAssembly if you need bulk numeric transforms.

Always profile before optimizing prematurely.

Conclusion

Converting JavaScript strings to integers is more than a one-size-fits-all task. You can choose parseInt() for partial parsing, Number() for strict conversion, or the unary plus for concise code. Watch out for edge cases like empty strings, leading zeros, or semicolon pitfalls. When working with JSON data, convert properties after parsing and validate the results. Finally, if performance matters, test each method in your environment. Armed with these tips, you’ll handle any string-to-int conversion cleanly and confidently.

Convert a JavaScript string to an integer using parseInt(), Number(), or unary plus operator, ensuring accurate number conversion in code.

Top comments (2)

Collapse
 
lionelrowe profile image
lionel-rowe

I think your benchmarking code is getting optimized away into nothingness (Chrome 137):

plus: 2.56201171875 ms
num: 2.423828125 ms
parse: 2.251953125 ms
Enter fullscreen mode Exit fullscreen mode

Those don't look plausible numbers for a million iterations of parsing a string to an integer, so more likely V8 has either figured out that the result is discarded and not bothered to calculate it, or has cached the results as it's always the same input so only needs to be calculated once, or both.

A better benchmark would be something like this:

function getRandomValues(array) {
    // 0x10_000 == 65_536.
    // See http://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#exceptions
    const max = Math.floor(0x10_000 / array.BYTES_PER_ELEMENT)

    for (let i = 0; i < array.length; i += max) {
        crypto.getRandomValues(array.subarray(i, i + max))
    }

    return array
}

const ITERATIONS = 1e7

function run(name, fn) {
    let n
    const inputs = [...getRandomValues(new Int32Array(ITERATIONS))].map(String)
    console.time(name)
    for (const s of inputs) n = fn(s)
    console.timeEnd(name)
}

run('plus', (s) => +s)
run('num', (s) => Number(s))
run('parse', (s) => parseInt(s, 10))
Enter fullscreen mode Exit fullscreen mode

Results aren't super stable for me (sometimes plus wins, sometimes num wins), but parseInt definitely seems a little slower. Typical results for ITERATIONS = 1e7 are something like this:

plus: 546.083984375 ms
num: 515.733154296875 ms
parse: 677.748046875 ms
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kiani0x01 profile image
Mateen Kiani • Edited

Good catch. I agree your approach for benchmarking is better as it's using random numbers instead of same number Everytime.
BTW what results do you get with 1e6 as I see you are using 1e7.

Also for and for of loop might also have some slight impact on scores.