Explain Codes LogoExplain Codes Logo

How to convert a string to an integer in JavaScript

javascript
string-conversion
parseint
number-function
Alex KataevbyAlex Kataev·Aug 11, 2024
TLDR

Your go-to solution is parseInt(string, radix). Specify radix as 10 to ensure decimal conversion, bypassing potential oddities.

const num = parseInt("42", 10); // Converts string '42' to number 42, not the answer to life, universe, and everything

For fractions in your strings, round with Math.floor(), Math.ceil(), or Math.round() post-conversion via parseFloat().

const intPart = Math.floor(parseFloat("42.99")); // Gets you 42, not your shoe size, hopefully

Unleash the Power of Plus and Number Function

The Unary Plus

The unary plus (+) is a quick-n-dirty way to convert strings to numbers. Sharp and crisp!

const quickNum = +"42"; // Gives you 42, not a mirror universe evil twin

Direct Conversion with Number

The Number() function offers a straight, no-detours method to get your job done:

const num = Number("42"); // Just 42, nothing less, nothing more

Round-it like it's Hot

Rounding your Strings

Numbers with decimals, Math.round() has got your back. It rounds to the nearest integer, while Math.floor() and its buddy Math.ceil() help you round down or up:

const roundNum = Math.round("42.5"); // Rounds '42.5' to 43, not to the closest star

The Edge, Not the U2 Guitarist

Watch out for Octals

parseInt(string, radix) plays a nasty trick when radix remains unsaid; it could assume octal. To avoid this, always use radix 10.

const withRadix = parseInt("010", 10); // Treats '010' as a human would, not an octal lover

Hey Non-Numeric!

parseInt() stops parsing when it bumps into a non-numeric character. Useful for strings with trailing non-numeric characters.

const nonNumeric = parseInt("100px", 10); // Sees 100px, reads 100, drops px like a hot potato

Advanced Potion Making

Let's Go Big! Oh Wait...

For 32-bit integers, bitwise operations like | or ~~ are zippy, but they may stumble with large numbers. Proceed with caution!

const bitwiseNum = "42" | 0; // Fast conversion, but not the 'answer' if number > 32-bits

Infinity and Beyond

Pay attention! parseInt() and Number() may not always see eye-to-eye with Infinity or exponential notation.

const infinityNum = parseInt("Infinity", 10); // Infinity is beyond parseInt's comprehension, returns NaN

Fast Age, Fast Conversion

Conversion speeds may vary. Refer to jsperf.com to find the fastest tactics for your specific requirement.

Handy Extras

Custom Functions

For situations beyond ordinary, a custom function wrapped around your conversion logic works great:

function toInteger(str) { if(str.startsWith('0') || isNaN(str)) return parseInt(str, 10); return +str; // Custom behaviour for other cases }

Safari's love for parseInt

In Safari, parseInt often beats other methods with its speedy conversion. Exactly, it's Safari fast!