[javascript] Javascript String to int conversion

I have the following JS immbedded in a page:

var round = Math.round;
var id = $(this).attr("id");

var len = id.length;
var indexPos = len -1; // index of the number so that we can split this up and used it as a title

var pasType = id.substring(0, indexPos); // adult, child or infant
var ind = round(id.substring(indexPos)); // converts the string index to an integer
var number = (id.substring(indexPos) + 1); // creates the number that will go in the title
window.alert(number);

id will be something like adult0, and I need to take that string and split it into adult and 0 - this part works fine.

The problem comes in when I try to increment the 0. As you can see I use Math.round to convert it to an integer, and then add 1 to it - I expect 0 to be 1 after this. However, it doesn't seem to be converting it to integer, because I get 01, not 1. When testing this with adult1 the alert I get is 11.

I'm using this question for reference, and have also tried var number += id.substring(indexPos);, which breaks the JS (unexpected identifier '+=')

Does anyone know what I'm doing wrong? Is there a better way of doing this?

This question is related to javascript string int type-conversion

The answer is


If you are sure id.substring(indexPos) is a number, you can do it like so:

var number = Number(id.substring(indexPos)) + 1;

Otherwise I suggest checking if the Number function evaluates correctly.


This is to do with JavaScript's + in operator - if a number and a string are "added" up, the number is converted into a string:

0 + 1; //1
'0' + 1; // '01'

To solve this, use the + unary operator, or use parseInt():

+'0' + 1; // 1
parseInt('0', 10) + 1; // 1

The unary + operator converts it into a number (however if it's a decimal it will retain the decimal places), and parseInt() is self-explanatory (converts into number, ignoring decimal places).

The second argument is necessary for parseInt() to use the correct base when leading 0s are placed:

parseInt('010'); // 8 in older browsers, 10 in newer browsers
parseInt('010', 10); // always 10 no matter what

There's also parseFloat() if you need to convert decimals in strings to their numeric value - + can do that too but it behaves slightly differently: that's another story though.


Although parseInt is the official function to do this, you can achieve the same with this code:

number*1

The advantage is that you save some characters, which might save bandwidth if your code has to lots of such conversations.


JS will think that the 0 is a string, which it actually is, to convert it to a int, use the: parseInt() function, like:

var numberAsInt = parseInt(number, 10);  
// Second arg is radix, 10 is decimal.

If the number is not possible to convert to a int, it will return NaN, so I would recommend a check for that too in code used in production or at least if you are not 100% sure of the input.


Convert by Number Class:-

Eg:

var n = Number("103");
console.log(n+1)

Output: 104

Note:- Number is class. When we pass string, then constructor of Number class will convert it.


Use parseInt():

var number = (parseInt(id.substring(indexPos)) + 1);` // creates the number that will go in the title

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 int

How can I convert a char to int in Java? How to take the nth digit of a number in python "OverflowError: Python int too large to convert to C long" on windows but not mac Pandas: Subtracting two date columns and the result being an integer Convert bytes to int? How to round a Double to the nearest Int in swift? Leading zeros for Int in Swift C convert floating point to int Convert Int to String in Swift Converting String to Int with Swift

Examples related to type-conversion

How can I convert a char to int in Java? pandas dataframe convert column type to string or categorical How to convert an Object {} to an Array [] of key-value pairs in JavaScript convert string to number node.js Ruby: How to convert a string to boolean Convert bytes to int? Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe SQL Server: Error converting data type nvarchar to numeric How do I convert a Python 3 byte-string variable into a regular string? Leading zeros for Int in Swift