How to convert a string to an integer in JavaScript
Asked Answered
B

33

2429

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

Big answered 15/7, 2009 at 20:22 Comment(5)
This page has a great table at the bottom that compares various methods of doing the conversion: medium.com/@nikjohn/…Amir
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).Saffren
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".Crispen
For non-standard locale (Ex. 123456789.123 is 123 456 789,12in fr-FR) see this discussionParnassus
To parse numbers with different numeral systems (for example, Persian/Farsi or Arabic), see this post and this post.Dabster
C
2918

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";

floor()

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");

parseFloat()

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"));

round()

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)
Contend answered 15/7, 2009 at 20:28 Comment(12)
For the last case, if you just want to truncate the number (round toward zero) you can still use parseInt. It will parse the number up to the period.Altruism
Yes. Any time I'm using "floor" much I do var floor=Math.floor which tightens things up a bit. I just wanted to show what happens with unary plus when you have a float. People run into trouble all the time because 1) People end up with strings when they want numbers. 2) JavaScript uses "+" for both addition and string concatenation.Contend
jsperf.com/performance-of-parseint/29 , hy @jedierikb i was edit jsperf link. Adding '4'>>0 and '4'>>>0.Benedetto
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/…Immoralist
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.Laurielaurier
Heads up. Both parseInt and parseFloat happily accepts letters. Only Number returns NaN consistently.Agribusiness
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.Taskmaster
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.Lowminded
Number(null) return 0 tooSuperfine
Before conversion, you may need to use a regular expression to check what type of number the string is. Positive Integer (no leading zeros): str.match(/^[1-9][0-9]*$/). Whole Number (zero or positive integer with no leading zeros): str.match(/^(0|[1-9][0-9]*)$/). Integer (no leading zeros): str.match(/^(0|-?[1-9][0-9]*)$/). Decimal (no leading zeros): str.match(/^(0|-?[1-9][0-9]*)\.[0-9]*$/). Any Number (no leading zeros): str.match(/^(0|-?[1-9][0-9]*)(\.[0-9]*)?$/). The expressions can be altered for other cases.Deland
Unary plus is preferred according to MDN.Impious
🆗,good but not enough . ``` Hereis 11 ways to convert a string to a number using JavaScript. using the Number() function using the parseInt() function using the parseFloat() function using the unary plus operator (+) multiplying the string by the number 1 dividing the string by the number 1 subtracting the number 0 from the string using the bitwise NOT operator (~) using the Math.floor() function using the Math.ceil() function using the Math.round() function from freecodecamp.org/news/… ```Milt
Y
291

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
Yonyona answered 15/7, 2009 at 20:23 Comment(5)
Radix is no longer required in 2016.Fredelia
It might not be for newer browsers but radix is still required for backwards compatibility.Evangelistic
Note that this ignores bad data after the number. For example, parseInt('0asdf', 10) produces 0.Intromission
LATEST: parseInt("010") == 10; // Returns true now - press ctrl-shift-j and paste that into your browser console to see for yourself :)Excoriate
let x = '5'; let y = +x; console.log(y); Output = 5Eccentricity
B
159

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

const 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 recognize, 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. The whitespace at the beginning of the string is ignored. Here's an example of it doing something different from what you want, and giving no indication that anything went wrong:

const 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 behavior 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 bit shift) will convert the value to a 32 bit 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 32 bits, 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 coercion 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 use case, 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).

Benny answered 11/12, 2013 at 7:47 Comment(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...Benny
@Benny should probably be .replace(/[^0-9.]/g, ""), otherwise "1.05" will become "105".Pack
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.Benny
I found using Number much more readable in code so thank you for pointing it out as a solution.Monkhood
@Benny 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");Medullary
@EduZamora good point. toFixed seems that it's best used for formatting rather than anything else.Benny
@Benny and J.Steve, in this whole long thread, yours is the only answer that address comma separators (e.g., "10,000" is = "10000"). This is quite a common occurrence, you should add this as an answer to the question (get credit for it)!Registered
S
63

Fastest

var x = "1000"*1;

Test

Here is little comparison of speed (macOS 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 fastest, 'number' is slowest (but results 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

I also tested var x = ~~"1000";. On Chrome and Safari, it is a little bit slower than var x = "1000"*1 (<1%), and on Firefox it is a little bit faster (<1%).

Spraddle answered 27/3, 2017 at 21:42 Comment(2)
There's no significant difference between the results of tests A, B, E and F - they're all essentially the same,Voussoir
I got ~~"1000" faster on Chrome, but they are all so closeSholokhov
F
59

ParseInt() and + are different.

parseInt("10.3456") // returns 10

+"10.3456" // returns 10.3456
Furious answered 14/3, 2012 at 9:54 Comment(2)
presumably +"..." is essentially Number("...").Crispen
Always specify the base: parseInt("10.3456", 10) if you don't want to have a surprise one of these days, cf developer.mozilla.org/en/docs/Web/JavaScript/Reference/… Be careful — this does not always default to 10!Fontanez
R
40

I use this way of converting string to number:

var str = "25";       // String
var number = str*1;   // Number

So, when multiplying by 1, the value does not change, but JavaScript 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

Ruthenium answered 16/3, 2014 at 18:24 Comment(1)
Please review Why not upload images of code/errors when asking a question? (e.g., "Images should only be used to illustrate problems that can't be made clear in any other way, such as to provide screenshots of a user interface.") and do the right thing (it covers answers and program output as well). Thanks in advance.Philanthropy
S
38

Try parseInt.

var number = parseInt("10", 10); //number will have value of 10.
Stove answered 15/7, 2009 at 20:23 Comment(1)
The proper answer to the questionSilence
F
31

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.

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
Fogged answered 16/1, 2013 at 9:51 Comment(1)
This only works for 32bit numbers. Bitwise operations will forcefully truncate larger values, so parseInt("4294967296") and ~~"4294967296" end up with different results. Namely, parseInt will return 4294967296 while ~~ will return 0.Muskogean
S
23

Please see the below example. It will help answer your question.

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.

Simoneaux answered 27/11, 2015 at 12:43 Comment(1)
Always specify the base: parseInt("20", 10) if you don't want to have a surprise one of these days, cf developer.mozilla.org/en/docs/Web/JavaScript/Reference/… Be careful — this does not always default to 10!Fontanez
P
20

In JavaScript, you can do the following:

ParseInt

parseInt("10.5") // Returns 10

Multiplying with 1

var s = "10";
s = s*1;  // Returns 10

Using the unary operator (+)

var s = "10";
s = +s;  // Returns 10

Using a bitwise operator

(Note: It starts to break after 2140000000. Example: ~~"2150000000" = -2144967296)

var s = "10.5";
s = ~~s; // Returns 10

Using Math.floor() or Math.ceil()

var s = "10";
s = Math.floor(s) || Math.ceil(s); // Returns 10
Paisano answered 25/3, 2021 at 11:2 Comment(2)
This is more or less a repeat of Nosredna's answer from 2009.Philanthropy
@PeterMortensen It didn't have bitwise operator and multiplying with 1Paisano
G
19

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
Gaulin answered 1/7, 2010 at 6:48 Comment(3)
Using parseInt wouldn't work right for a float. parseFloat works properly in this case.Gonroff
This is a valid concern - even parseInt("2e2") which is an integer, would be 200 if parseInt understood exponential notation, but actually returns 2, because it doesn't.Benny
@Benny - IMHO it is not reasonable to expect parseInt to comprehend a float representation. More appropriate to parseFloat or Number, then round or truncate to int as desired. That is a clearer statement of intent.Crispen
D
13

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.

Deepfry answered 13/6, 2015 at 5:36 Comment(1)
The question was "How do I convert a String into an integer in javascript"Chef
Y
13

We can use +(stringOfNumber) instead of using parseInt(stringOfNumber).

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

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

Yeh answered 7/7, 2015 at 12:51 Comment(6)
But you cannot use it in formulas! I.e. (1+("21"))*10 === 1210 !Prurient
@AlexanderVasilyev I think you can, wouldn't you just use an extra parenthesis around the +?Susannesusceptibility
@NiCkNewman I get +("21") from the example in the answer we comment.Prurient
I really dislike this solution. It's not explicit like parseInt is. A common implementation is const myNumber = +myNumberAsAString which looks like a standard += or =+ operator at first glance. Also If used incorrectly it could lead to concatenation errors. This solution is based on the fact that 0 is assumed as the left-hand side when no number is provided.Cabretta
I agree with @StormMuller. If for some reason a coder wishes more brevity than parseInt, with one more character can make it a bit clearer: 0+"...". That makes it easier to not misunderstand what the result will be, however it still requires some mental thought. So still "smells". Clean coding is saying what you mean: use parseInt.Crispen
The question is how to convert a string to an integer. Unary plus however is my favorite way of converting to a number because it's the most concise, and it converts everything except bigints.Upholsterer
H
13

There are many ways in JavaScript to convert a string to a number value... All are 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.

Hardball answered 30/5, 2017 at 12:43 Comment(0)
E
12

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
Engine answered 16/7, 2009 at 20:5 Comment(2)
The third example causes a SyntaxError, you should use a double dot, e.g.: 2..toInt(); the first dot will end the representation of a Number literal and the second dot is the property accessor.Cheeseparing
this question isn't about mootools it's about JavaScript.Seidel
D
11

String to Number in JavaScript:

Unary + (most recommended)

  • +numStr is easy to use and has better performance compared with others
  • Supports both integers and decimals
console.log(+'123.45') // => 123.45

Some other options:

Parsing Strings:

  • parseInt(numStr) for integers
  • parseFloat(numStr) for both integers and decimals
console.log(parseInt('123.456')) // => 123
console.log(parseFloat('123'))   // => 123

JavaScript Functions

  • Math functions like round(numStr), floor(numStr), ceil(numStr) for integers

  • Number(numStr) for both integers and decimals

console.log(Math.floor('123'))     // => 123
console.log(Math.round('123.456')) // => 123
console.log(Math.ceil('123.454'))  // => 124
console.log(Number('123.123'))     // => 123.123

Unary Operators

  • All basic unary operators, +numStr, numStr-0, 1*numStr, numStr*1, and numStr/1

  • All support both integers and decimals

  • Be cautious about numStr+0. It returns a string.

console.log(+'123')  // => 123
console.log('002'-0) // => 2
console.log(1*'5')   // => 5
console.log('7.7'*1) // => 7.7
console.log(3.3/1)   // =>3.3
console.log('123.123'+0, typeof ('123.123' + 0)) // => 123.1230 string

Bitwise Operators

  • Two tilde ~~numStr or left shift 0, numStr<<0
  • Supports only integers, but not decimals
console.log(~~'123')      // => 123
console.log('0123'<<0)    // => 123
console.log(~~'123.123')  // => 123
console.log('123.123'<<0) // => 123

// Parsing
console.log(parseInt('123.456')) // => 123
console.log(parseFloat('123'))   // => 123

// Function
console.log(Math.floor('123'))     // => 123
console.log(Math.round('123.456')) // => 123
console.log(Math.ceil('123.454'))  // => 124
console.log(Number('123.123'))     // => 123.123

// Unary
console.log(+'123')  // => 123
console.log('002'-0) // => 2
console.log(1*'5')   // => 5
console.log('7.7'*1) // => 7.7
console.log(3.3/1)   // => 3.3
console.log('123.123'+0, typeof ('123.123'+0)) // => 123.1230 string

// Bitwise
console.log(~~'123')      // => 123
console.log('0123'<<0)    // => 123
console.log(~~'123.123')  // => 123
console.log('123.123'<<0) // => 123
Dispensary answered 9/7, 2022 at 13:9 Comment(2)
This is more or less a repeat of previous answers.Philanthropy
Basically consolidation of all posible options that I know which also syncs with previous answers.Dispensary
R
10

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

Repertory answered 30/10, 2015 at 2:21 Comment(3)
@AlexanderYau, per this doc, the '1' will be converted to 1 by ToNumber, then 1 - 0 would be 1Repertory
What do the ">" prompts imply? What environment?Philanthropy
@PeterMortensen, the > prompots is from the console of Chrome.Repertory
T
10

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
Tacho answered 27/3, 2017 at 15:12 Comment(2)
Returning Not A Number is a bit aggressive for a float, don't you think?Asoka
It's parseInteger, not parseNumber. I guess every solutions is a workaround since JS does not support integers and floats as separate types. We could return null instead of NaN, if Not A Number is misleading.Taskmaster
H
10

Here is the easiest solution

let myNumber = "123" | 0;

More easy solution

let myNumber = +"123";
Hutcherson answered 6/6, 2019 at 13:22 Comment(0)
I
9

The easiest way would be to use + like this

const strTen = "10"
const numTen = +strTen      // string to number conversion
console.log(typeof strTen)  // string
console.log(typeof numTen)  // number
Immortal answered 18/8, 2021 at 21:40 Comment(1)
That is very likely already covered in previous answers.Philanthropy
S
7

I actually needed to "save" a string as an integer, for a binding between C and JavaScript, so I convert the string into an 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:
        maximum 4 characters, 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;
}
Shirr answered 7/11, 2016 at 16:5 Comment(1)
That's an interesting way to store and retrieve 4-byte values. It doesn't answer the conventional interpretation of the question: how to convert a string representation of a number into an integer value. Regardless, your int2str function stops if a byte is 0, which could be a legitimate element within the value, so the if...break should be removed so you get a complete 4-byte value returned.Buddhology
B
5
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);
}
Byebye answered 30/7, 2019 at 15:4 Comment(1)
However, be aware that Number supports some special formats, that parseInt will incorrectly interpret. For example, Number("0x11") => 17, then parseInt will return 0. It might be better to search for non-digits, if goal is to reject all non-Integers. Or could do var f = Number(str); return f.isInteger() ? f : NaN; Depending on exactly what you want to allow/reject.Crispen
D
4

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
Demona answered 1/7, 2019 at 8:48 Comment(0)
D
3

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

i.e: 123 = 100+20+3 = 1100 + 2+10 + 31 = 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;
}
Devilmaycare answered 16/5, 2019 at 18:59 Comment(0)
J
3

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.

Juxon answered 9/11, 2019 at 6:56 Comment(1)
Could you please explain what + is in this case and how the casting happens?Saar
Q
3

Number()

Number(" 200.12 ")  // Returns 200.12

Number("200.12")  // Returns 200.12

Number("200") // Returns 200

parseInt()

parseInt(" 200.12 ")  // Return 200

parseInt("200.12")  // Return 200

parseInt("200") // Return 200

parseInt("Text information") // Returns NaN

parseFloat()

It will return the first number

parseFloat("200 400")  // Returns 200

parseFloat("200") // Returns 200

parseFloat("Text information") // Returns NaN

parseFloat("200.10")  // Return 200.10

Math.floor()

Round a number to the nearest integer

Math.floor(" 200.12 ")  // Return 200

Math.floor("200.12")  // Return 200

Math.floor("200") // Return 200
Quant answered 22/3, 2022 at 6:24 Comment(0)
U
1

As of ES2015 you can use Math.trunc() to convert strings to integer:

Math.trunc("33.33") // returns 33
Math.trunc("-5999999999.99999") // returns -5999999999

Or, if you need to support old browsers or you just prefer to avoid using a function, you can use the remainder operator trick to get the remainder when dividing by 1, then subtract. Unlike the answers that use bitwise operators, this successfully handles large numbers (with the exception of Infinity which becomes NaN.)

var a = "-5999999999.99999"
a-=a%1// converts a to -5999999999

Finally, if you need to handle Infinity, there is this split trick that works with non-negative numbers by splitting on a decimal point thereby removing the decimal portion of the string followed by converting to a number with unary +. This also works when converting strings without decimals:

var a = "5999999999.99999"
a = +a.split(".")[0];// converts a to 5999999999

Note that all of the above solutions will convert an empty string to 0. If that's not what you want then you need to check for that condition first.

Upholsterer answered 27/2, 2024 at 21:19 Comment(0)
S
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
Stepha answered 17/1, 2018 at 22:16 Comment(1)
Perhaps elaborate in your answer? Why does that work? (But *********** without *********** "Edit:", "Update:", or similar - the answer should appear as if it was written today.)Philanthropy
M
0

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

+"052254" // 52254
Mediator answered 10/3, 2019 at 20:55 Comment(1)
This is already covered in a previous answer, Nosredna's answer.Philanthropy
O
-1

All of the previous answers are correct. Please be sure before that this is a number in a string by doing "typeot x === 'number'". Otherwise, it will return NaN.

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

var num1 = "12423";
typeof num1 => 'number';
+num1 = > 12423`
Overeager answered 30/3, 2017 at 7:4 Comment(2)
In node v8.5.0, var num1 = "12423"; typeof num1; returns string.Medullary
If your goal is to avoid NaN, then the straightforward solution is to test the value you get back for NaN: var v = whatever-conversion-you-prefer(s); if (isNaN(v)) ...handle the error... else ...use v....Crispen
H
-1

function doSth(){
  var a = document.getElementById('input').value;
  document.getElementById('number').innerHTML = toNumber(a) + 1;
}
function toNumber(str){
  return +str;
}
<input id="input" type="text">
<input onclick="doSth()" type="submit">
<span id="number"></span>
Hexose answered 4/4, 2017 at 17:3 Comment(0)
R
-1

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

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

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.

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))
Rosel answered 9/12, 2020 at 0:3 Comment(0)
S
-2

I use this

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

var str = "7";
var num = str.toInt(); // outputs 7, if not str outputs -1
//or
var num = str.toInt(0); // outputs 7, if not str outputs 0

This way I always get an int back.

Stringed answered 17/8, 2018 at 16:53 Comment(1)
Why does it need to be so complex?Philanthropy

© 2022 - 2025 — McMap. All rights reserved.