faqts : Computers : Programming : Languages : JavaScript : Language Core : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

59 of 93 people (63%) answered Yes
Recently 6 of 10 people (60%) answered Yes

Entry

How can I convert a string to a number?
How can I add form field numerical values?

Jan 15th, 2003 17:37
Robert Taylor, Martin Honnen,


Javascript has the
  parseInt(string, base)
and
  parseFloat(string)
functions to convert a string to a number. The base argument of 
parseInt allows to convert depending on the number system base so to 
parse binary input e.g.
  var binString = '101';
use
  var number = parseInt(binString, 2);
For normal decimal numbers use base 10 e.g.
  parseInt('42', 10); 
The parseInt and parseFloat functions are in particular helpful for 
processing numerical form input as 
  <INPUT>
  <SELECT>/<OPTION>
  <TEXTAREA>
HTML elements all have string values so for example to add two text 
fields you use
  parseFloat(document.formName.field1.value)  
    parseFloat(document.formName.field2.value)
Besides using parseInt or parseFloat you can also enforce conversion to 
a number by substracting 0 or multiplying with 1 for instance
  var string = '42';
  var number = string - 0;
or
  var number = string * 1;
or
  var string2 = '3';
  var number = string - ( - string2); // Adds string and string2 = '45'
This last method is important because ECMAScript pathologically couples 
the "+" operator with string concatenation and mathematical addition. 
Remember, subtracting a negative equals adding a positive. . .