# Numeric value problems

Discussion in 'Javascript' started by chumley, Jan 19, 2010.

1. ### chumleyGuest

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

chumley, Jan 19, 2010

2. ### Evertjan.Guest

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 type='submit' value='calculate'>
</form>
===========================================

--
Evertjan.
The Netherlands.

Evertjan., Jan 19, 2010

3. ### Erwin MollerGuest

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

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 (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

Erwin Moller, Jan 19, 2010
4. ### Dmitry A. SoshnikovGuest

On Jan 19, 11:31 pm, chumley <> wrote:
> 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(parseInt(a, 10) + parseInt(b, 10)); // number
alert(+a + +b); // also number, faster than parseInt, but in this case

/ds

Dmitry A. Soshnikov, Jan 19, 2010
5. ### RobGGuest

chumley wrote:
> 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 >

--
Rob

RobG, Jan 19, 2010
6. ### chumleyGuest

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....

On Jan 19, 12:31 pm, chumley <> wrote:
> 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

chumley, Jan 20, 2010
7. ### Scott SauyetGuest

On Jan 19, 8:00 pm, chumley <> wrote:
> 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

Scott Sauyet, Jan 20, 2010
8. ### Lasse Reichstein NielsenGuest

Scott Sauyet <> writes:

> "+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
--
Lasse Reichstein Holst Nielsen
'Javascript frameworks is a disruptive technology'

Lasse Reichstein Nielsen, Jan 20, 2010
9. ### Scott SauyetGuest

On Jan 20, 4:12 pm, Lasse Reichstein Nielsen <>
wrote:
> Scott Sauyet <> writes:
> > "+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

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

Scott Sauyet, Jan 20, 2010
10. ### David MarkGuest

On Jan 20, 4:55 pm, Scott Sauyet <> wrote:
> On Jan 20, 4:12 pm, Lasse Reichstein Nielsen <>
> wrote:
>
> > Scott Sauyet <> writes:
> > > "+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

>
> 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.
>

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?

David Mark, Jan 20, 2010
11. ### Thomas 'PointedEars' LahnGuest

David Mark wrote:

> Scott Sauyet wrote:
>> Lasse Reichstein Nielsen wrote:
>> > 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.

>
> 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
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
-- Bjoern Hoehrmann

Thomas 'PointedEars' Lahn, Jan 20, 2010
12. ### David MarkGuest

On Jan 20, 6:48 pm, Thomas 'PointedEars' Lahn <>
wrote:
> David Mark wrote:
> > Scott Sauyet wrote:
> >> Lasse Reichstein Nielsen wrote:
> >> > 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.

>
> > 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.

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.

David Mark, Jan 21, 2010
13. ### Thomas 'PointedEars' LahnGuest

David Mark wrote:

> Thomas 'PointedEars' Lahn wrote:
>> David Mark wrote:
>> > 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.

>
> 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.

>> 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.

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
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f806at\$ail\$1\$>

Thomas 'PointedEars' Lahn, Jan 21, 2010
14. ### Lasse Reichstein NielsenGuest

Scott Sauyet <> writes:

> On Jan 20, 4:12 pm, Lasse Reichstein Nielsen <>
> wrote:

>> 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?

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

/L
--
Lasse Reichstein Holst Nielsen
'Javascript frameworks is a disruptive technology'

Lasse Reichstein Nielsen, Jan 21, 2010
15. ### Scott SauyetGuest

On Jan 21, 1:06 pm, Lasse Reichstein Nielsen <>
wrote:
> Scott Sauyet <> writes:
>> On Jan 20, 4:12 pm, Lasse Reichstein Nielsen <>
>> wrote:
>>> 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?

>
> 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

Scott Sauyet, Jan 21, 2010
16. ### JorgeGuest

On Jan 20, 4:36 pm, Scott Sauyet <> wrote:
> On Jan 19, 8:00 pm, chumley <> wrote:
>
> > 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.

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

Jorge, Jan 21, 2010
17. ### Scott SauyetGuest

On Jan 21, 4:22 pm, Jorge <> wrote:
>> "+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/

How many browsers did you test? It was faster for me in FF and
Chrome, but not in Opera, IE, or Safari.

-- Scott

Scott Sauyet, Jan 21, 2010
18. ### Dmitry A. SoshnikovGuest

On Jan 22, 12:22 am, Jorge <> wrote:
> On Jan 20, 4:36 pm, Scott Sauyet <> wrote:
>
>
>
> > On Jan 19, 8:00 pm, chumley <> wrote:

>
> > > 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.

>
> 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

Dmitry A. Soshnikov, Jan 22, 2010
19. ### JorgeGuest

On Jan 22, 11:10 am, "Dmitry A. Soshnikov"
<> wrote:
> On Jan 22, 12:22 am, Jorge <> wrote:
>
>
>
>
>
> > On Jan 20, 4:36 pm, Scott Sauyet <> wrote:

>
> > > On Jan 19, 8:00 pm, chumley <> wrote:

>
> > > > 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.  Eitheris
> > > 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/

>
> 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,
--
Jorge.

Jorge, Jan 22, 2010
20. ### JorgeGuest

On Jan 22, 3:12 pm, Jorge <> wrote:
>
> 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

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
--
Jorge.

Jorge, Jan 22, 2010