SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Thread: numerical array

  1. #1
    SitePoint Zealot
    Join Date
    Mar 2011
    Posts
    146
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    numerical array

    Hi,

    Can anyone help me convert the inputs to numbers instead of strings?
    I'm trying to make a calculator of sorts

    var array = new Array();

    function insert(val)
    {
    array[array.length]=val;
    }

    function show()
    {
    var string="";
    for(i = 0; i < array.length; i++)

    document.getElementById("e").value = string=string+array[i]+"\n";

    }

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,678
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    One of the effective ways is to pass the value through the Number object. If it's not a valid number, it will return NaN (not a number).
    Since NaN is a falsy value, you can use the OR operator to provide a default value of 0 if no valid number can be made.

    Code javascript:
    var string = field.value;
    var number = Number(string) || 0.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •