[javascript] How to convert a string to an integer in JavaScript?

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

This question is related to javascript string integer data-conversion

The answer is


all of the above are correct. Please be sure before that this is a number in a string by doing "typeot x === 'number'" other wise it will return NaN

 var num = "fsdfsdf242342";
 typeof num => 'string';

 var num1 = "12423";
 typeof num1 => 'number';
 +num1 = > 12423`

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

_x000D_
_x000D_
function doSth(){_x000D_
  var a = document.getElementById('input').value;_x000D_
  document.getElementById('number').innerHTML = toNumber(a) + 1;_x000D_
}_x000D_
function toNumber(str){_x000D_
  return +str;_x000D_
}
_x000D_
<input id="input" type="text">_x000D_
<input onclick="doSth()" type="submit">_x000D_
<span id="number"></span>
_x000D_
_x000D_
_x000D_


Here is the easiest solution

let myNumber = "123" | 0;

More easy solution

let myNumber = +"123";

There are many ways in JavaScript to convert a string to a number value... All simple and handy, choose the way which one works for you:

var num = Number("999.5"); //999.5
var num = parseInt("999.5", 10); //999
var num = parseFloat("999.5"); //999.5
var num = +"999.5"; //999.5

Also any Math operation converts them to number, for example...

var num = "999.5" / 1; //999.5
var num = "999.5" * 1; //999.5
var num = "999.5" - 1 + 1; //999.5
var num = "999.5" - 0; //999.5
var num = Math.floor("999.5"); //999
var num = ~~"999.5"; //999

My prefer way is using + sign, which is the elegant way to convert a string to number in JavaScript.


Google gave me this answer as result, so...

I actually needed to "save" a string as an integer, for a binding between C and JavaScript, so I convert the string into a integer value:

/*
    Examples:
        int2str( str2int("test") ) == "test" // true
        int2str( str2int("t€st") ) // "t¬st", because "€".charCodeAt(0) is 8364, will be AND'ed with 0xff
    Limitations:
        max 4 chars, so it fits into an integer
*/
function str2int(the_str) {
    var ret = 0;
    var len = the_str.length;
    if (len >= 1) ret += (the_str.charCodeAt(0) & 0xff) <<  0;
    if (len >= 2) ret += (the_str.charCodeAt(1) & 0xff) <<  8;
    if (len >= 3) ret += (the_str.charCodeAt(2) & 0xff) << 16;
    if (len >= 4) ret += (the_str.charCodeAt(3) & 0xff) << 24;
    return ret;
}
function int2str(the_int) {
    var tmp = [
        (the_int & 0x000000ff) >>  0,
        (the_int & 0x0000ff00) >>  8,
        (the_int & 0x00ff0000) >> 16,
        (the_int & 0xff000000) >> 24
    ];
    var ret = "";
    for (var i=0; i<4; i++) {
        if (tmp[i] == 0)
            break;
        ret += String.fromCharCode(tmp[i]);
    }
    return ret;
}

ParseInt() and + are different

parseInt("10.3456") // returns 10

+"10.3456" // returns 10.3456

Please see the below example.It will help clear your doubt

Example                  Result

parseInt("4")            4
parseInt("5aaa")         5
parseInt("4.33333")      4
parseInt("aaa");         NaN (means "Not a Number")

by using parseint function It will only give op of integer present and not the string


In my opinion, no answer covers all edge cases as parsing a float should result in an error.

function parseInteger(value) {
    if(value === '') return NaN;
    const number = Number(value);
    return Number.isInteger(number) ? number : NaN;
}
parseInteger("4")            // 4
parseInteger("5aaa")         // NaN
parseInteger("4.33333")      // NaN
parseInteger("aaa");         // NaN

I use this

String.prototype.toInt = function (returnval) { 
    var i = parseInt(this);
    return isNaN(i) ? returnval !== undefined ? returnval : - 1  :      i; 
}

this way I always get an int back.


Though an old question, but maybe this can be helpful to someone.

I use this way of converting string to int number

var str = "25";       // string
var number = str*1;   // number

So, when multiplying by 1, the value does not change, but js automatically returns a number.

But as it is shown below, this should be used if you are sure that the str is a number(or can be represented as a number), otherwise it will return NaN - not a number.

you can create simple function to use, e.g.

function toNumber(str) {
   return str*1;
}

enter image description here


we can use +(stringOfNumber) instead of using parseInt(stringOfNumber)

Ex: +("21") returns int of 21 like the parseInt("21").

we can use this unary "+" operator for parsing float too...


function parseIntSmarter(str) {
    // ParseInt is bad because it returns 22 for "22thisendsintext"
    // Number() is returns NaN if it ends in non-numbers, but it returns 0 for empty or whitespace strings.
    return isNaN(Number(str)) ? NaN : parseInt(str, 10);
}

Also as a side note: Mootools has the function toInt() which is used on any native string (or float (or integer)).

"2".toInt()   // 2
"2px".toInt() // 2
2.toInt()     // 2

This (probably) isn't the best solution for parsing an integer, but if you need to "extract" one, for example:

"1a2b3c" === 123
"198some text2hello world!30" === 198230
// ...

this would work (only for integers):

_x000D_
_x000D_
var str = '3a9b0c3d2e9f8g'

function extractInteger(str) {
  var result = 0;
  var factor = 1

  for (var i = str.length; i > 0; i--) {
    if (!isNaN(str[i - 1])) {
      result += parseInt(str[i - 1]) * factor
      factor *= 10
    }
  }

  return result
}

console.log(extractInteger(str))
_x000D_
_x000D_
_x000D_

Of course, this would also work for parsing an integer, but would be slower than other methods.

You could also parse integers with this method and return NaN if the string isn't a number, but I don't see why you'd want to since this relies on parseInt internally and parseInt is probably faster.

_x000D_
_x000D_
var str = '3a9b0c3d2e9f8g'

function extractInteger(str) {
  var result = 0;
  var factor = 1

  for (var i = str.length; i > 0; i--) {
    if (isNaN(str[i - 1])) return NaN
    result += parseInt(str[i - 1]) * factor
    factor *= 10
  }

  return result
}

console.log(extractInteger(str))
_x000D_
_x000D_
_x000D_


To convert a String into Integer, I recommend using parseFloat and NOT parseInt. Here's why:

Using parseFloat:

parseFloat('2.34cms')  //Output: 2.34
parseFloat('12.5')     //Output: 12.5
parseFloat('012.3')    //Output: 12.3

Using parseInt:

parseInt('2.34cms')  //Output: 2
parseInt('12.5')     //Output: 12
parseInt('012.3')    //Output: 12

So if you have noticed parseInt discards the values after the decimals, whereas parseFloat lets you work with floating point numbers and hence more suitable if you want to retain the values after decimals. Use parseInt if and only if you are sure that you want the integer value.


I posted the wrong answer here, sorry. fixed.

This is an old question, but I love this trick:

~~"2.123"; //2
~~"5"; //5

The double bitwise negative drops off anything after the decimal point AND converts it to a number format. I've been told it's slightly faster than calling functions and whatnot, but I'm not entirely convinced.

EDIT: Another method I just saw here (a question about the javascript >>> operator, which is a zero-fill right shift) which shows that shifting a number by 0 with this operator converts the number to a uint32 which is nice if you also want it unsigned. Again, this converts to an unsigned integer, which can lead to strange behaviors if you use a signed number.

"-2.123" >>> 0; // 4294967294
"2.123" >>> 0; // 2
"-5" >>> 0; // 4294967291
"5" >>> 0; // 5

Beware if you use parseInt to convert a float in scientific notation! For example:

parseInt("5.6e-14") 

will result in

5 

instead of

0

I only added one plus(+) before string and that was solution!

+"052254" //52254

Hope it helps ;)


Try parseInt.

var number = parseInt("10", 10); //number will have value of 10.

Summing the multiplication of digits with their respective power of ten:

i.e: 123 = 100+20+3 = 1*100 + 2+10 + 3*1 = 1*(10^2) + 2*(10^1) + 3*(10^0)

function atoi(array) {

// use exp as (length - i), other option would be to reverse the array.
// multiply a[i] * 10^(exp) and sum

let sum = 0;

for (let i = 0; i < array.length; i++) {
    let exp = array.length-(i+1);
    let value = array[i] * Math.pow(10,exp);
    sum+=value;
}

return sum;

}


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).


Try str - 0 to convert string to number.

> str = '0'
> str - 0
  0
> str = '123'
> str - 0
  123
> str = '-12'
> str - 0
  -12
> str = 'asdf'
> str - 0
  NaN
> str = '12.34'
> str - 0
  12.34

Here are two links to compare the performance of several ways to convert string to int

https://jsperf.com/number-vs-parseint-vs-plus

http://phrogz.net/js/string_to_number.html


You can use plus. For example:

var personAge = '24';
var personAge1 = (+personAge)

then you can see the new variable's type bytypeof personAge1 ; which is number.


Fastest

var x = "1000"*1;

Test

Here is little comparison of speed (Mac Os only)... :)

For chrome 'plus' and 'mul' are fastest (>700,000,00 op/sec), 'Math.floor' is slowest. For Firefox 'plus' is slowest (!) 'mul' is fastest (>900,000,000 op/sec). In Safari 'parseInt' is fastes, 'number' is slowest (but resulats are quite similar, >13,000,000 <31,000,000). So Safari for cast string to int is more than 10x slower than other browsers. So the winner is 'mul' :)

You can run it on your browser by this link https://jsperf.com/js-cast-str-to-number/1

enter image description here

Update

I also test var x = ~~"1000"; - on Chrome and Safari is a little bit slower than var x = "1000"*1 (<1%), on Firefox is a little bit faster (<1%). I update above picture and test


The safest way to ensure you get a valid integer:

let integer = (parseInt(value, 10) || 0);

Examples:

// Example 1 - Invalid value:
let value = null;
let integer = (parseInt(value, 10) || 0);
// => integer = 0
// Example 2 - Valid value:
let value = "1230.42";
let integer = (parseInt(value, 10) || 0);
// => integer = 1230
// Example 3 - Invalid value:
let value = () => { return 412 };
let integer = (parseInt(value, 10) || 0);
// => integer = 0

Another option is to double XOR the value with itself:

var i = 12.34;
console.log('i = ' + i);
console.log('i ? i ? i = ' + (i ^ i ^ i));

This will output:

i = 12.34
i ? i ? i = 12

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to integer

Python: create dictionary using dict() with integer keys? How to convert datetime to integer in python Can someone explain how to append an element to an array in C programming? How to get the Power of some Integer in Swift language? python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" What's the difference between integer class and numeric class in R PostgreSQL: ERROR: operator does not exist: integer = character varying C++ - how to find the length of an integer Converting binary to decimal integer output Convert floats to ints in Pandas?

Examples related to data-conversion

python pandas dataframe columns convert to dict key and value how to convert long date value to mm/dd/yyyy format Convert string with comma to integer How do I print bytes as hexadecimal? Convert String with Dot or Comma as decimal separator to number in JavaScript Java string to date conversion Java: How to convert List to Map How do I convert this list of dictionaries to a csv file? Converting array to list in Java Convert 4 bytes to int