Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

over riding string concatonation

Status
Not open for further replies.

punkRik

Technical User
Mar 15, 2007
2
GB
Hi. Im trying to do some simple addition with a form using javascript but instead of adding the variables it concatonates there values. Any idea how i can stop this?

the script is on here users.aber.ac.uk/rsh6/assignment%201/purchases.html

its a crude site i know, just something to get me started with the language...

any help appreciated, thanks..!
 
parseInt() and parseFloat() are your friends.

Code:
var stringNumber1 = "1234";
var stringNumber2 = "4321";

var concatenationExample = stringNumber1 + stringNumber2;

var additionExample = parseInt(stringNumber1) + parseInt(stringNumber2);

alert("String Concatenation Result: " + concatenationExample + "\n\nInteger Addition Result: " + additionExample);

parseInt of course being for integer numbers, parseFloat if you need a floating point number.

Never be afraid to share your dreams with the world.
There's nothing the world loves more than the taste of really sweet dreams.

Enable Apps
 
Thanks! Its an improvement anyway, now i'm just getting the NaN (not a number) message as an output in my result. Any idea how to repair this?

thanks!
 
Yeah, make sure the string you're parsing is a number.
When you alert the parseInt value from b you get NaN - since "abc" is obviously not a number (unless you're dealing with hex)
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
<title>title test</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript">

var a = "123";
var b = "abc";

alert(parseInt(a, 10));
alert(parseInt(b, 10));

</script>
<style type="text/css"></style>
</head>
<body>

</body>
</html>

-kaht

Looking for a puppy? [small](Silky Terriers are hypoallergenic dogs that make great indoor pets due to their lack of shedding and small size)[/small]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top