How to convert a string to an integer in JavaScript
Your go-to solution is parseInt(string, radix)
. Specify radix as 10 to ensure decimal conversion, bypassing potential oddities.
For fractions in your strings, round with Math.floor()
, Math.ceil()
, or Math.round()
post-conversion via parseFloat()
.
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!
Direct Conversion with Number
The Number()
function offers a straight, no-detours method to get your job done:
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:
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.
Hey Non-Numeric!
parseInt()
stops parsing when it bumps into a non-numeric character. Useful for strings with trailing non-numeric characters.
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!
Infinity and Beyond
Pay attention! parseInt()
and Number()
may not always see eye-to-eye with Infinity
or exponential notation.
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:
Safari's love for parseInt
In Safari, parseInt
often beats other methods with its speedy conversion. Exactly, it's Safari fast!
Was this article helpful?