473,388 Members | 1,385 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

Changing strings to numbers(easy...maybe)

Hi,

Im trying to add 3 numbers together, instead of getting 1+2+3=6, I'm
getting 123, how could I remedy this.

ManyThanks in advance

Michael

<html>
<head>
<title>Summation Template File</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<script language="JavaScript">
function addUp() {
var a,b,c,sum;
a = document.fred.aaa.value; // extract the string of text typed into
the input box
b = document.fred.bbb.value;
c = document.fred.ccc.value;
// the problem is on the next line, all the other lines are OK and
shouldn't be changed
sum =a+b+c ;
window.alert("The sum is "+sum);
}
</script>
</head>

<body bgcolor="#FFFFFF" text="#000000">
<form name="fred">
<input type="text" name="aaa" size="5">
<input type="text" name="bbb" size="5">
<input type="text" name="ccc" size="5">
<input type="button" value="Sum Data" onClick="addUp();">
</form>
</body>
</html>
Jul 23 '05 #1
11 3599
MickG wrote:
Hi,

Im trying to add 3 numbers together, instead of getting 1+2+3=6, I'm
getting 123, how could I remedy this.


use parseInt(number) to get a number

Kae
Jul 23 '05 #2
MickG wrote on 28 feb 2005 in comp.lang.javascript:
Im trying to add 3 numbers together, instead of getting 1+2+3=6, I'm
getting 123, how could I remedy this.


var a='1' // string !
var b='2' // string !
var c='3' // string !

r = a + b + c

alert(r) // returns string 123

r = +a + +b + +c

alert(r) // returns number 6

r = 1*a + 1*b + 1*c

alert(r) // returns number 6
--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Jul 23 '05 #3
> I'm trying to add 3 numbers together, instead of getting 1+2+3=6, I'm
getting 123, how could I remedy this. a = document.fred.aaa.value; // extract the string of text typed into
// the input box
b = document.fred.bbb.value;
c = document.fred.ccc.value;
// the problem is on the next line, all the other lines are OK and
// shouldn't be changed
sum =a+b+c ;


sum = (+a) + (+b) + (+c);

See http://www.crockford.com/javascript/survey.html

If you leave out the parens, it could look like

sum = +a++b++c;

which would be very bad. It is better to be clear.
Jul 23 '05 #4
Kae Verens wrote:

To the OP: In future please read the FAQ before posting. See
<URL:http://jibbering.com/faq/>.

[snip]
use parseInt(number) to get a number


parseInt(number, radix)

is almost always preferred.

There are faster ways to coerce a string to a number, namely unary plus:

+str1 + +str2

With the brief snippet shown by the OP, I'd suggest checking the
format of the user input before using it. Whilst parseInt will behave
somewhat sensibly when parsing a non-numeric string, it isn't very
useful to start adding NaNs.

function isInteger(s) {return /^(0|[1-9]\d*)$/.test(s);}

function sum(f) {
var e = f.elements,
a = e['a'],
b = e['b'],
c = e['c'];

if(!isInteger(a)) {
/* Instruct user that input A is invalid. */
return false;
}
if(!isInteger(b)) {
/* Instruct user that input B is invalid. */
return false;
}
if(!isInteger(c)) {
/* Instruct user that input C is invalid. */
return false;
}
e['total'].value = +a + +b + +c;
}

<form action="">
<input type="text" name="a">
<input type="text" name="b">
<input type="text" name="c">
<input type="text" name="total">
<input type="button" value="Sum" onclick="sum(this.form);">
</form>

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #5
Kae Verens wrote:
MickG wrote:

Hi,

Im trying to add 3 numbers together, instead of getting 1+2+3=6, I'm
getting 123, how could I remedy this.

use parseInt(number) to get a number


No. You use the unary + to get a number, depending on what you define as
a number.

parseInt('08') is a very prime example of the flaw of parseInt when not
used with a radix.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Jul 23 '05 #6
Or this !!

sum = (a-0) + (b-0) + (c-0);

Jul 23 '05 #7
MickG wrote:
Hi,

Im trying to add 3 numbers together, instead of getting 1+2+3=6, I'm
getting 123, how could I remedy this.


<URL:http://www.jibbering.com/faq/#FAQ4_21>

--
Rob
Jul 23 '05 #8
mike wrote:
Or this !!

sum = (a-0) + (b-0) + (c-0);


No, you should read this groups FAQ first.

Had you done that, you would have prevented at least two problems with
your post. I will leave it to you as an exercise to determine what those
problems are.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Jul 23 '05 #9
JRS: In article <1a**************************@posting.google.com >,
dated Mon, 28 Feb 2005 11:45:00, seen in news:comp.lang.javascript,
MickG <mi*****@hotmail.com> posted :
Im trying to add 3 numbers together,
No, you are not. You are adding 3 strings (probably; at least one is a
string).
instead of getting 1+2+3=6, I'm
getting 123, how could I remedy this.
By reading the newsgroup FAQ.

Michael : Matches to /^-\d+$/ are integers too.
Douglas : sum = (+a) + (+b) + (+c);
If you leave out the parens, it could look like
sum = +a++b++c;


When I leave them out, it looks like
sum = +a + +b + +c;
All:

"Numeric strings" commonly come from reading input controls.

In such cases it is often good to write

var Wotsit = + nameofWotsitcontrol.value
var Al = + nameofAlcontrol.value
var ...
// expression(s) using Wotsit /et al/

Firstly, the desired values are obtained in the desired form; after
that, they are used in expressions which are not cluttered by control
addressing. The gain on clarity will generally outweigh any minor loss
in performance.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #10
Dr John Stockton wrote:

[snip]
Michael : Matches to /^-\d+$/ are integers too.


Yes. It would be acceptable to prefix the number with a plus, too.

Perhaps I should have named the function, isPositiveDecimalInteger,
but that seems a little excessive. :)

[snip]

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #11
JRS: In article <11**********************@f14g2000cwb.googlegroups .com>
, dated Mon, 28 Feb 2005 16:00:02, seen in news:comp.lang.javascript,
mike <hi****@charter.net> posted :
Or this !!

sum = (a-0) + (b-0) + (c-0);


Even sum = -(-a-b-c) is better than that (and is fairly short).

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
by: Krakatioison | last post by:
My sites navigation is like this: http://www.newsbackup.com/index.php?n=000000000040900000 , depending on the variable "n" (which is always a number), it will take me anywhere on the site......
11
by: Michael B. Allen | last post by:
Coming from C and Java on *nix I'm a little out of my element messing around with CList and MSVC++ but I think my issues are largely syntactic. I have an ADT that I use called a 'varray' that can...
89
by: purifier | last post by:
The problem is to write a program in 'C' to find the greatest of 2 given numbers... Easy? huh here's the catch do not use 'if' or any conditional statements if u want it to be a little more...
4
by: rossum | last post by:
I was comparing strings, as one does: stringA.CompareTo(stringB) == -1 Then I thought that this was not as easy to read as it could be, wouldn't it be clearer to write: stringA < stringB ...
3
by: Schüle Daniel | last post by:
Hello NG, recently I was using Scheme and Ruby and was really nicely surprised to find there support for the computing with rational numbers for example this how it works in Ruby ...
23
by: ultimatewarrior | last post by:
Hi all, first of all I beg your pardon if this question has been asked before, but I was unable to find anything in the past posts. I have written a piece of code that was supposed to be quite...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.