How to Convert a String to an Integer in JavaScript

How to convert a string to an integer in JavaScript?

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)

How to convert object properties string to integer in javascript

This should do the work:

var obj = {

ob1: {

id: "21",

width: "100",

height: "100",

name: "image1"

},

ob2: {

id: "22",

width: "300",

height: "200",

name: "image2"

}

}

function convertIntObj(obj) {

const res = {}

for (const key in obj) {

res[key] = {};

for (const prop in obj[key]) {

const parsed = parseInt(obj[key][prop], 10);

res[key][prop] = isNaN(parsed) ? obj[key][prop] : parsed;

}

}

return res;

}

var result = convertIntObj(obj);

console.log('Object result', result)

var arrayResult = Object.values(result);

console.log('Array result', arrayResult)

Convert string to either integer or float in javascript

That's how I finally solved it. I didn't find any other solution than to add the variable type to the variable ...

var obj = {

a: '2',

b: '2.1',

c: '2.0',

d: 'text'

};

// Explicitly remember the variable type

for (key in obj) {

var value = obj[key], type;

if ( isNaN(value) || value === "" ) {

type = "string";

}

else {

if (value.indexOf(".") === -1) {

type = "integer";

}

else {

type = "float";

}

value = +value; // Convert string to number

}

obj[key] = {

value: value,

type: type

};

}

document.write("<pre>" + JSON.stringify(obj, 0, 4) + "</pre>");

How to convert a string to number in TypeScript?

Exactly like in JavaScript, you can use the parseInt or parseFloat functions, or simply use the unary + operator:

var x = "32";
var y: number = +x;

All of the mentioned techniques will have correct typing and will correctly parse simple decimal integer strings like "123", but will behave differently for various other, possibly expected, cases (like "123.45") and corner cases (like null).

Conversion table
Table taken from this answer

How to convert a long string (more than 16 digits) into numbers

Just expanding on my above comment with another solution...

You've exceeded the maximum safe integer value. (Number.MAX_SAFE_INTEGER, which equals 9007199254740991). Numbers larger than this are not supported with standard integer types in javascript, or rather there's not enough precision to represent them. Anything larger than this is represented in scientific notation and the extra digits are truncated and represented only as zeroes.

With that said, you don't even need to convert the array to a string to an integer just to increment it. You can just increment the individual digits in the array, starting at the end and working your way forwards to "carry the 1" so to speak.

var plusOne = function(digits) {
for(let i = digits.length - 1; i > -1; i--)
{
if(digits[i] == 9)
{
digits[i] = 0;
if(i == 0)
digits = [1].concat(digits);
}
else
{
digits[i]++;
break;
}
}
return digits;
};

console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]));

How to convert a string of comma separated numbers to integers?

First split the values with comma using the split() method like this.

arr.split(',')

After that you will get each value separated in an array which will be accessible by giving array index. So arr[0] will include 108 and arr[1] will include 109. Now all that's left to do is parse them individually.

parseInt(arr[0]) 
parseInt(arr[1])

Javascript convert string to integer

Basic Answer

The reason parseInt is not working is because of the comma. You could remove the comma using a regex such as:

var num = '1,700.00';

num = num.replace(/\,/g,'');

This will return a string with a number in it. Now you can parseInt. If you do not choose a radix it will default to 10 which was the correct value to use here.

num = parseInt(num);

Do this for each of your string numbers before adding them and everything should work.

More information

How the replace works:

More information on replace at mdn:

`/` - start  
`\,` - escaped comma
`/` - end
`g` - search globally

The global search will look for all matches (it would stop after the first match without this)

'' replace the matched sections with an empty string, essentially deleting them.

Regular Expressions

  • A great tool to test regular expressions: Rubular and more info about them at mdn
  • If you are looking for a good tutorial here is one.

ParseInt and Rounding, parseFloat

parseInt always rounds to the nearest integer. If you need decimal places there are a couple of tricks you can use. Here is my favorite:

2 places: `num = parseInt(num * 100) / 100;`
3 places: `num = parseInt(num * 1000) / 1000;`

For more information on parseInt look at mdn.

parseFloat could also be used if you do not want rounding. I assumed you did as the title was convert to an integer. A good example of this was written by @fr0zenFry below. He pointed out that parseFloat also does not take a radix so it is always in base10. For more info see mdn.



Related Topics



Leave a reply



Submit