Categories
data-conversion integer javascript string

How to convert a string to an integer in JavaScript?

2136

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

5

  • 4

    This page has a great table at the bottom that compares various methods of doing the conversion: medium.com/@nikjohn/…

    Mar 11, 2020 at 9:12


  • 1

    In absence of OP’s clarification, this question could be interpreted in the sense of converting any string to a number, i.e. turning “dog” into a number (which of course can be done).

    Aug 18, 2020 at 11:32

  • 1

    Taking the bait: @DanielCarrera .. and yet no one here interpreted the question that way. Probably because if that was the goal, it would very likely have been worded quite differently. After all, the process of doing so (“hashing”) is not, nor has ever been, AFAIK, referred to as “converting to an integer”.

    Aug 27, 2020 at 0:03


  • For non-standard locale (Ex. 123456789.123 is 123 456 789,12in fr-FR) see this discussion

    – vsync

    Sep 5, 2020 at 8:43


  • To parse numbers with different numeral systems (for example, Persian/Farsi or Arabic), see this post and this post.

    – Mahozad

    Dec 24, 2021 at 15:16

2596

The simplest way would be to use the native Number function:

var x = Number("1000")

If that doesn’t work for you, then there are the parseInt, unary plus, parseFloat with floor, and Math.round methods.

parseInt:

var x = parseInt("1000", 10); // you want to use radix 10
    // so you get a decimal number even with a leading 0 and an old browser ([IE8, Firefox 20, Chrome 22 and older][1])

unary plus
if your string is already in the form of an integer:

var x = +"1000";

if your string is or might be a float and you want an integer:

var x = Math.floor("1000.01"); //floor automatically converts string to number

or, if you’re going to be using Math.floor several times:

var floor = Math.floor;
var x = floor("1000.01");

If you’re the type who forgets to put the radix in when you call parseInt, you can use parseFloat and round it however you like. Here I use floor.

var floor = Math.floor;
var x = floor(parseFloat("1000.01"));

Interestingly, Math.round (like Math.floor) will do a string to number conversion, so if you want the number rounded (or if you have an integer in the string), this is a great way, maybe my favorite:

var round = Math.round;
var x = round("1000"); //equivalent to round("1000",0)

11

  • 7

    Update to 2015: as of ECMAScript 5, strings with a leading zero “0” also get default radix 10, instead of 8. Explicitly specifying radix 10 is only necessary for older browsers. kangax.github.io/compat-table/es5/…

    – Grilse

    Jul 30, 2015 at 10:31

  • 45

    Note that Number(”) succeeds (returning 0), even though most people wouldn’t consider the empty string to represent a valid number. And parseInt(‘3q’) succeeds (returning 3) even though most people wouldn’t consider ‘3q’ to be a valid number.

    Sep 3, 2015 at 22:15

  • 8

    Heads up. Both parseInt and parseFloat happily accepts letters. Only Number returns NaN consistently.

    Mar 14, 2017 at 9:39

  • 6

    In my opinion, parsing an integer should result with exception/NaN for every value which is not exactly an integer. Therefore none of these work as Number('2.2') coerces to 2 and Number('') coerce to 0.

    Mar 27, 2017 at 15:23

  • 2

    parseInt(“6-4”) returns 6, whereas Number(“6-4”) returns NaN…. this could be a significant different if you’re testing strings that might be guids, for example.

    Jun 6, 2017 at 15:31

266

Try parseInt function:

var number = parseInt("10");

But there is a problem. If you try to convert “010” using parseInt function, it detects as octal number, and will return number 8. So, you need to specify a radix (from 2 to 36). In this case base 10.

parseInt(string, radix)

Example:

var result = parseInt("010", 10) == 10; // Returns true

var result = parseInt("010") == 10; // Returns false

Note that parseInt ignores bad data after parsing anything valid.
This guid will parse as 51:

var result = parseInt('51e3daf6-b521-446a-9f5b-a1bb4d8bac36', 10) == 51; // Returns true

5

  • 4

    Radix is no longer required in 2016.

    – user663031

    Oct 1, 2016 at 21:23

  • 8

    It might not be for newer browsers but radix is still required for backwards compatibility.

    Jan 20, 2017 at 14:21

  • 4

    Note that this ignores bad data after the number. For example, parseInt('0asdf', 10) produces 0.

    – Sam

    Apr 19, 2018 at 1:08

  • LATEST: parseInt(“010”) == 10; // Returns true now – press ctrl-shift-j and paste that into your browser console to see for yourself 🙂

    – OCDev

    May 22 at 18:06

  • let x = ‘5’; let y = +x; console.log(y); Output = 5

    Aug 1 at 5:55


145

There are two main ways to convert a string to a number in javascript. One way is to parse it and the other way is to change its type to a Number. All of the tricks in the other answers (e.g. unary plus) involve implicitly coercing the type of the string to a number. You can also do the same thing explicitly with the Number function.

Parsing

var parsed = parseInt("97", 10);

parseInt and parseFloat are the two functions used for parsing strings to numbers. Parsing will stop silently if it hits a character it doesn’t recognise, which can be useful for parsing strings like “92px”, but it’s also somewhat dangerous, since it won’t give you any kind of error on bad input, instead you’ll get back NaN unless the string starts with a number. Whitespace at the beginning of the string is ignored. Here’s an example of it doing something different to what you want, and giving no indication that anything went wrong:

var widgetsSold = parseInt("97,800", 10); // widgetsSold is now 97

It’s good practice to always specify the radix as the second argument. In older browsers, if the string started with a 0, it would be interpreted as octal if the radix wasn’t specified which took a lot of people by surprise. The behaviour for hexadecimal is triggered by having the string start with 0x if no radix is specified, e.g. 0xff. The standard actually changed with ecmascript 5, so modern browsers no longer trigger octal when there’s a leading 0 if no radix has been specified. parseInt understands radixes up to base 36, in which case both upper and lower case letters are treated as equivalent.

Changing the Type of a String to a Number

All of the other tricks mentioned above that don’t use parseInt, involve implicitly coercing the string into a number. I prefer to do this explicitly,

var cast = Number("97");

This has different behavior to the parse methods (although it still ignores whitespace). It’s more strict: if it doesn’t understand the whole of the string than it returns NaN, so you can’t use it for strings like 97px. Since you want a primitive number rather than a Number wrapper object, make sure you don’t put new in front of the Number function.

Obviously, converting to a Number gives you a value that might be a float rather than an integer, so if you want an integer, you need to modify it. There are a few ways of doing this:

var rounded = Math.floor(Number("97.654"));  // other options are Math.ceil, Math.round
var fixed = Number("97.654").toFixed(0); // rounded rather than truncated
var bitwised = Number("97.654")|0;  // do not use for large numbers

Any bitwise operator (here I’ve done a bitwise or, but you could also do double negation as in an earlier answer or a bitshift) will convert the value to a 32bit integer, and most of them will convert to a signed integer. Note that this will not do want you want for large integers. If the integer cannot be represented in 32bits, it will wrap.

~~"3000000000.654" === -1294967296
// This is the same as
Number("3000000000.654")|0
"3000000000.654" >>> 0 === 3000000000 // unsigned right shift gives you an extra bit
"300000000000.654" >>> 0 === 3647256576 // but still fails with larger numbers

To work correctly with larger numbers, you should use the rounding methods

Math.floor("3000000000.654") === 3000000000
// This is the same as
Math.floor(Number("3000000000.654"))

Bear in mind that coeercion understands exponential notation and Infinity, so 2e2 is 200 rather than NaN, while the parse methods don’t.

Custom

It’s unlikely that either of these methods do exactly what you want. For example, usually I would want an error thrown if parsing fails, and I don’t need support for Infinity, exponentials or leading whitespace. Depending on your usecase, sometimes it makes sense to write a custom conversion function.

Always check that the output of Number or one of the parse methods is the sort of number you expect. You will almost certainly want to use isNaN to make sure the number is not NaN (usually the only way you find out that the parse failed).

6

  • 7

    It depends whether you want your code to also accept 97,8,00 and similar or not. A simple trick is to do a .replace(/[^0-9]/g, "") which will remove all non digits from your string and then do the conversion afterwards. This of course will ignore all kinds of crazy strings that you should probably error on rather than just parse…

    Feb 5, 2015 at 0:09


  • 6

    @kybernetikos should probably be .replace(/[^0-9.]/g, ""), otherwise “1.05” will become “105”.

    – J.Steve

    Jun 8, 2015 at 17:18


  • Quite right, although I wouldn’t use something like that for important code anyway – there are so many ways it can let something through you really don’t want to let through.

    Jun 11, 2015 at 8:07

  • 3

    I found using Number much more readable in code so thank you for pointing it out as a solution.

    Sep 7, 2016 at 18:16

  • 2

    @kybernetikos In var fixed = Number("97.654").toFixed(0); // rounded rather than truncated, we are getting a string (because of the .toFixed method) instead of a number (integer). If we want the rounded integer it’s probably better to just use Math.round("97.654");

    Feb 17, 2018 at 9:58