Numeric value problems

C

chumley

I have a function that simply totals the value from previous
calculations from textboxes, but when trying to add the totals up
after assigning each textbox value a variable,the total in my
grandtotal box is just the values appended to each other (i.e . If
value A is 150 and value B is 200, the grandtotal box displays 150200:

function calculate2(oform, prefix) {
var A = document.oform.vn_stVis.value;
var B = document.oform.ja_stVis.value;
var C = document.oform.ta_stVis.value;
var D = document.oform.sa_stVis.value;
//var E = (A + B + C + D); -- this just appends the total literally to
each other in grandtotal box

var E = (A + B + C + D);
document.oform.gt_stVis.value = E;
}


??
chumley
 
E

Evertjan.

chumley wrote on 19 jan 2010 in comp.lang.javascript:
I have a function that simply totals the value from previous
calculations from textboxes, but when trying to add the totals up
after assigning each textbox value a variable,the total in my
grandtotal box is just the values appended to each other (i.e . If
value A is 150 and value B is 200, the grandtotal box displays 150200:

function calculate2(oform, prefix) {

What do you want to do with "prefix"?

It seems to me this is not yor code,
but that you are using code from someone else without understanding it.
var A = document.oform.vn_stVis.value;
var B = document.oform.ja_stVis.value;
var C = document.oform.ta_stVis.value;
var D = document.oform.sa_stVis.value;

These A B C and D will contain strings strings.
//var E = (A + B + C + D); -- this just appends the total literally to
each other in grandtotal box

Indeed.

Why the () they do not help anything.
var E = (A + B + C + D);

You woyuld first have to change the strings to numeric values,
like:

A = +A;

If the string is not converteble to a numeric value,
you will get NaN:

var E = +A + +B + +C + +D;
document.oform.gt_stVis.value = E;
}

The long and strange names you give,
will deter you from understanding,
keep it simple, try this:

============== test.html ===================
<script type='text/javascript'>

function calc(f) {
f.e.value = +f.a.value + +f.b.value +
+f.c.value + +f.d.value;
return false; // to prevent submission.
};

</script>

<form onsubmit='return calc(this)'>
<br><input name='a'> a
<br><input name='b'> b
<br><input name='c'> c
<br><input name='d'> d
<br><br><input name='e' readonly> result
<br><br><input type='submit' value='calculate'>
</form>
===========================================
 
E

Erwin Moller

chumley schreef:
I have a function that simply totals the value from previous
calculations from textboxes, but when trying to add the totals up
after assigning each textbox value a variable,the total in my
grandtotal box is just the values appended to each other (i.e . If
value A is 150 and value B is 200, the grandtotal box displays 150200:

function calculate2(oform, prefix) {
var A = document.oform.vn_stVis.value;
var B = document.oform.ja_stVis.value;
var C = document.oform.ta_stVis.value;
var D = document.oform.sa_stVis.value;
//var E = (A + B + C + D); -- this just appends the total literally to
each other in grandtotal box

var E = (A + B + C + D);
document.oform.gt_stVis.value = E;
}


??
chumley

Hi,

That happens because the values from your textfields are threated as
strings.
And by an unlucky coincedence JavaScript uses the + sign for string
concatenation and for adding.

Solution: Simply cast the strings to numbers using:
parseInt() for integers
or parseFloat() for floating point numbers

Warning: If you use parseInt be sure to supply the radix (propably 10).

In short:
var num1 = "23";
var num2 = "11";

alert (num1+num2); // 2311
alert (parseInt(num1,10) + parseInt(num2,10)); // 34

Regards,
Erwin Moller

--
"There are two ways of constructing a software design: One way is to
make it so simple that there are obviously no deficiencies, and the
other way is to make it so complicated that there are no obvious
deficiencies. The first method is far more difficult."
-- C.A.R. Hoare
 
D

Dmitry A. Soshnikov

I have a function that simply totals the value from previous
calculations from textboxes, but when trying to add the totals up
after assigning each textbox value a variable,the total in my
grandtotal box is just the values appended to each other (i.e . If
value A is 150 and value B is 200, the grandtotal box displays 150200:

function calculate2(oform, prefix) {
var A = document.oform.vn_stVis.value;
var B = document.oform.ja_stVis.value;
var C = document.oform.ta_stVis.value;
var D = document.oform.sa_stVis.value;
//var E = (A + B + C + D); -- this just appends the total literally to
each other in grandtotal box

var E = (A + B + C + D);
document.oform.gt_stVis.value = E;

}

??


That because with string (and values from textboxes are strings) "+"
is used as concatenation. To use "+" for the numeric mathematical
meaning, use manual type conversion to numbers (e.g. function parseInt
(...) or unary "+" operator):

var
form = document.forms['oform'],
a = form.elements['vn_stVis'].value, // string
b = form.elements['ja_stVis'].value; // also string

alert(a + b); // string
alert(parseInt(a, 10) + parseInt(b, 10)); // number
alert(+a + +b); // also number, faster than parseInt, but in this case
is less readable

/ds
 
R

RobG

chumley said:
I have a function that simply totals the value from previous
calculations from textboxes, but when trying to add the totals up
after assigning each textbox value a variable,the total in my
grandtotal box is just the values appended to each other (i.e . If
value A is 150 and value B is 200, the grandtotal box displays 150200:

You've already got a number of answers, but just to round out the
discussion the answer is in the FAQ:

5.4 Why does 1+1 equal 11? or How do I convert a string to a number?
<URL: http://www.jibbering.com/faq/#typeConvert >
 
C

chumley

thanks for responses. i was able to add a little math to force the
variable to be numeric:

var A = document.oform.vn_stVis.value * 1;
var B = document.oform.ja_stVis.value * 1;
.....etc....
 
S

Scott Sauyet

thanks for responses. i was able to add a little math to force the
variable to be numeric:

var A = document.oform.vn_stVis.value * 1;
var B = document.oform.ja_stVis.value * 1;
....etc....

Although that works, you should probably take the advice you came here
seeking. :)

"parseInt"/"parseFloat" are the most explicit way to do the
conversion, the unitary "+" is probably the most efficient. Either is
more recognizable and hence more easily maintainable than yours.

"+myVar" does a numeric conversion only.

"myVar * 1" does a numeric conversion followed by a multiplication.

Cheers,

-- Scott
 
L

Lasse Reichstein Nielsen

Scott Sauyet said:
"+myVar" does a numeric conversion only.

"myVar * 1" does a numeric conversion followed by a multiplication.

An optimizing implementation might recognize the futility of
multiplying by one and just do the numeric conversion :)

Personally I prefer using "Number(myVar)" for readability, even though
the prefix plus is usually slightly faster (it doesn't need to look up
"Number" in the global object and call the function). Speed is only
important if it's not fast enough.

/L
 
S

Scott Sauyet

An optimizing implementation might recognize the futility of
multiplying by one and just do the numeric conversion :)

Have you ever seen an optimizer that smart, though? :)
Personally I prefer using "Number(myVar)" for readability, even though
the prefix plus is usually slightly faster (it doesn't need to look up
"Number" in the global object and call the function). Speed is only
important if it's not fast enough.

Yes, there is much to be said for that version too. It's at least as
explicit as parseInt, and it doesn't risk getting lost in middle of
punctuation noise.

-- Scott
 
D

David Mark

Have you ever seen an optimizer that smart, though? :)


Yes, there is much to be said for that version too. It's at least as
explicit as parseInt, and it doesn't risk getting lost in middle of
punctuation noise.

As for parseInt vs. Number (or +), it depends on what you allow for
the input. Do you want "100px" to translate to 100 or is it an error?
 
T

Thomas 'PointedEars' Lahn

David said:
As for parseInt vs. Number (or +), it depends on what you allow for
the input. Do you want "100px" to translate to 100 or is it an error?

Not an error, but the result would be NaN.

And do you want "0x12" to translate to 18, or "012" to 10? The former is
what Number() and parseInt() without explicit base does, the latter what
Number() and _unary_ `+' do in older implementations, and what parseInt()
without explicit base does even in recent implementations.


PointedEars
 
D

David Mark

Not an error, but the result would be NaN.

A _validation_ error, which would be determined by checking for the
NaN result. In other words, do you let "100px" pass or not?
And do you want "0x12" to translate to 18, or "012" to 10? The former is
what Number() and parseInt() without explicit base does, the latter what
Number() and _unary_ `+' do in older implementations, and what parseInt()
without explicit base does even in recent implementations.

Never use it without an explicit base. That's one of about a hundred
reasons I run every script I work with through JSLint.
 
T

Thomas 'PointedEars' Lahn

David said:
A _validation_ error, which would be determined by checking for the
NaN result. In other words, do you let "100px" pass or not?

Fair enough.
Never use it without an explicit base. That's one of about a hundred
reasons I run every script I work with through JSLint.

That appears to be a wise course of action: While ES3F left it to the
implementation whether or not to support octal notation with parseInt()
without explicit base, ES5 denies that possibility.


PointedEars
 
L

Lasse Reichstein Nielsen

Scott Sauyet said:
On Jan 20, 4:12 pm, Lasse Reichstein Nielsen <[email protected]>
wrote:

Have you ever seen an optimizer that smart, though? :)

Not that exact optimization. I have seen optimizations for, e.g.,
bitwise or and xor with zero.

/L
 
S

Scott Sauyet

Not that exact optimization. I have seen optimizations for, e.g.,
bitwise or and xor with zero.

Have you? I guess for languages like C/C++ or Java, or other
languages meant for heavy-weight lifting, this makes a good deal of
sense. I've never run across it before. Have you seen it for dynamic
languages? I imagine "eval" might erect barriers to many
optimizations that might otherwise be possible.

-- Scott
 
J

Jorge

Although that works, you should probably take the advice you came here
seeking.  :)

"parseInt"/"parseFloat" are the most explicit way to do the
conversion, the unitary "+" is probably the most efficient.  Either is
more recognizable and hence more easily maintainable than yours.

"+myVar" does a numeric conversion only.

"myVar * 1" does a numeric conversion followed by a multiplication.

Currently, parseInt(txt, 10) is faster (~2x) in any browser.
http://jorgechamorro.com/cljs/061/
 
D

Dmitry A. Soshnikov

Currently, parseInt(txt, 10) is faster (~2x) in any browser.http://jorgechamorro.com/cljs/061/

Thanks for the test, Jorge. But actually, at current moment "strange"
implementation of unary plus operator for that purpose have only FF
and Chrome. By the algorithm parseInt (15.1.2.2) (on first sight) is
more complex than unary plus (11.4.6) for numeric conversion. Thinking
so, we can suggest that unary plus conversion is faster than parseInt
- and that's what exactly we have in some other current browsers (at
least in IE8, Opera 10.10 and Safari (4.0.3 WinXP)). But as this all
are implementations - they can do it as they want with some
optimizations/regressions.

Also interesting result is that parseInt(...) without radix is faster
than with radix 10 - as some default value on implementation level
will be taken without parsing radix (but not in Chrome again - there
it's slower).

/ds
 
J

Jorge

Thanks for the test, Jorge. But actually, at current moment "strange"
implementation of unary plus operator for that purpose have only FF
and Chrome. By the algorithm parseInt (15.1.2.2) (on first sight) is
more complex than unary plus (11.4.6) for numeric conversion. Thinking
so, we can suggest that unary plus conversion is faster than parseInt
- and that's what exactly we have in some other current browsers (at
least in IE8, Opera 10.10 and Safari (4.0.3 WinXP)). But as this all
are implementations - they can do it as they want with some
optimizations/regressions.

Also interesting result is that parseInt(...) without radix is faster
than with radix 10 - as some default value on implementation level
will be taken without parsing radix (but not in Chrome again - there
it's slower).

In my Mac, with OSX 10.6.2, parseInt(txt, 10) is the fastest in any
browser:

http://jorgechamorro.com/cljs/061/20100122/safari.png
http://jorgechamorro.com/cljs/061/20100122/chrome.png
http://jorgechamorro.com/cljs/061/20100122/opera.png
http://jorgechamorro.com/cljs/061/20100122/firefox.png

Cheers,
 
J

Jorge


Safari Version 4.0.4 (6531.21.10, r53596)
Opera Version 10.50 pre-alpha Build 8166
Firefox 3.6 Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:
1.9.2) Gecko/20100115 Firefox/3.6
Chrome 4.0.249.49
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top