Welcome to Our Community

Wanting to join the rest of our members? Feel free to sign up today.

Anyone know a bit of Javascript?

Discussion in 'The Lounge' started by Budo, Jan 29, 2008.

  1. Budo

    Budo Raging Clue

    Joined:
    Sep 19, 2007
    Messages:
    727
    Likes Received:
    9
    Location:
    Canadia
    I have a form where the user inputs a number, selects a size, and then the total is displayed in a third box. The problem is, I want the total to be formatted to two decimal places. The answer has to be simple, but I can't find anything:

    <script language = JavaScript>

    function calculate()

    {

    A = document.form1.txtFirstNumber.value
    B = document.form1.txtSecondNumber.value

    A = Number(A)
    B = Number(B)
    C = (A * B )
    document.form1.txtThirdNumber.value = C

    }

    </script>
     
  2. [DT]

    [DT] Gearhead Surf Coder

    Joined:
    Aug 30, 2007
    Messages:
    1,314
    Likes Received:
    28
    Location:
    Vilano Beach, FL
    Is the Javascript parser later than 1.5? Then you can use a nice built-in function: toFixed()

    Like so:

    var v = 25.567;
    return v.toFixed(2);

    (which will return 25.56)

    Again, this is specifically for later JS implementations.

    Oh BTW, if you need a function for earlier JS, I'm sure I have something - I used to use the Math.Round() function (which rounded up to the nearest int) with a little creative math to pad the decimal places (simple * and / by a factor of 10).

    Also you might want to check for a numeric value (isNan(), or parse out the numeric portion parseInt(), or parseFloat()).
     
    #2 [DT], Jan 29, 2008
    Last edited: Jan 29, 2008
  3. Budo

    Budo Raging Clue

    Joined:
    Sep 19, 2007
    Messages:
    727
    Likes Received:
    9
    Location:
    Canadia
    It's after 1.5.

    Thanks, I'll give that a try
     
  4. [DT]

    [DT] Gearhead Surf Coder

    Joined:
    Aug 30, 2007
    Messages:
    1,314
    Likes Received:
    28
    Location:
    Vilano Beach, FL

    No problem.

    You might also want to use the later DOM for finding elements vs. having to traverse a tree:

    document.getElementById()

    Then you can short form the element/object like so:

    var f_name = document.getElementById('TextBoxFirstName');

    var f_val = f_name.value;

    f_val.style.display = 'block';

    Handy if you need to get/set properties for the element in a few places.
     

Share This Page