44

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);
2
  • you need to use regexp to filter out non-numbers and then use parseInt() Commented May 28, 2012 at 6:16
  • Why is php tagged on this question? Commented May 28, 2012 at 6:19

4 Answers 4

104

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

Sign up to request clarification or add additional context in comments.

1 Comment

What if number contains -? E.g. -123.00
7

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?

Comments

2
str1 = "test123.00";
str2 = "yes50.00";
intStr1 = str1.replace(/[A-Za-z$-]/g, "");
intStr2 = str2.replace(/[A-Za-z$-]/g, "");
total = parseInt(intStr1)+parseInt(intStr2);

alert(total);

working Jsfiddle

Comments

-2

Is this logically possible??.. I guess the approach that you must take is this way :

Str1 ="test123.00"
Str2 ="yes50.00"

This will be impossible to tackle unless you have delimiter in between test and 123.00

eg: Str1 = "test-123.00" 

Then you can split this way

Str2 = Str1.split("-"); 

This will return you an array of words split with "-"

Then you can do parseFloat(Str2[1]) to get the floating value i.e 123.00

1 Comment

It can do without delimiter.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.