Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Integer value from a String using javascript/jquery [duplicate]

These are the strings I have:

"test123.00" "yes50.00" 

I want to add the 123.00 with 50.00.

How can I do this?

I used the command parseInt() but it displays NaN error in alert box.

This is the code:

 str1 = "test123.00";  str2 = "yes50.00";  total = parseInt(str1)+parseInt(str2);  alert(total); 
like image 251
Kichu Avatar asked May 28 '12 06:05

Kichu


People also ask

How to get integer value from string in jQuery?

Find code to convert String to Integer using jQuery. To convert, use JavaScript parseInt() function which parses a string and returns an integer. var sVal = '234'; var iNum = parseInt(sVal); //Output will be 234.

How to find integer value from string in JavaScript?

In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.

How to duplicate a string in JavaScript?

repeat() is an inbuilt function in JavaScript which is used to build a new string containing a specified number of copies of the string on which this function has been called. Syntax: string. repeat(count);

How check value is integer or not in jQuery?

Answer: Use the jQuery. isNumeric() method You can use the jQuery $. isNumeric() method to check whether a value is numeric or a number. The $. isNumeric() returns true only if the argument is of type number, or if it's of type string and it can be coerced into finite numbers, otherwise it returns false .


2 Answers

just do this , you need to remove char other than "numeric" and "." form your string will do work for you

yourString = yourString.replace ( /[^\d.]/g, '' ); 

your final code will be

  str1 = "test123.00".replace ( /[^\d.]/g, '' );   str2 = "yes50.00".replace ( /[^\d.]/g, '' );   total = parseInt(str1, 10) + parseInt(str2, 10);   alert(total); 

Demo

like image 61
Pranay Rana Avatar answered Oct 16 '22 09:10

Pranay Rana


For parseInt to work, your string should have only numerical data. Something like this:

 str1 = "123.00";  str2 = "50.00";  total = parseInt(str1)+parseInt(str2);  alert(total); 

Can you split the string before you start processing them for a total?

like image 41
nunespascal Avatar answered Oct 16 '22 09:10

nunespascal