Connecting Tech Pros Worldwide Forums | Help | Site Map

getting the numeric value of a variable

Member
 
Join Date: Feb 2007
Posts: 95
#1: Apr 20 '09
I have a webpage that allows insurance agents to enter a group of trucks for an insurance policy. I want to keep track of the number of power units (tractors or trucks), the number of trailers and the total insured value (the sum of all the units' values). So for power units, if the unit being entered is a tractor or a truck I have a variable, nPowerUnits, that increments like this
Expand|Select|Wrap|Line Numbers
  1.  
  2. nPowerUnits=nPowerUnits+1;
  3.  
  4.  
That variable works fine, as does nTrailers. However if I do the same thing with the total insured value Javascript concatenates the values rather than adding them numerically. Thus,
Expand|Select|Wrap|Line Numbers
  1. nTIV=nTIV+document.getElementById('value'+i).value;
  2.  
results in "0, 01000,0100020000" beginning with the original value of 0 and adding, first 1000, then 20000. The correct answer should be 21000. I have tried using the number() function, as in
Expand|Select|Wrap|Line Numbers
  1. var nValue=document.getElementById('value'+x).value;
  2.       nTIV=number(nTIV)+nValue;
  3.                 number(nTIV)=number(nTIV)+number(nValue);
  4.  
and so on but I get an 'object expected' error.

How can I add two variable values and get a number instead of a string?

Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North
Posts: 5,137
#2: Apr 20 '09

re: getting the numeric value of a variable


You need a Capital "N" for Number.

Try the following:
Expand|Select|Wrap|Line Numbers
  1. var nValue=document.getElementById('value'+x).value;
  2. //nTIV=Number(nTIV)+nValue;
  3. nTIV=Number(nTIV)+Number(nValue);
acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#3: Apr 21 '09

re: getting the numeric value of a variable


...or use parseInt().
Reply