SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Zealot
    Join Date
    Sep 2010
    Posts
    131
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Change a variable into a number format

    I am new.

    When I try to add a variable and a number from a textbox they add as strings:

    var m=(window.document.myform.mo.value);
    var b=m+24

    if m=12 then I get b=1224

    Now when I add number to it I get an error in the page:

    var m=number(window.document.myform.mo.value);
    var b=m+24

    I am sure all the other code is correct.

    How do you change a variable into a number format?

  2. #2
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,068
    Mentioned
    153 Post(s)
    Tagged
    2 Thread(s)
    Use parseInt

    Code JavaScript:
    var m=parseInt(window.document.myform.mo.value, 10);
    var b=m+24

    Rémon - Hosting Advisor

    SitePoint forums will switch to Discourse soon! Make sure you're ready for it!

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy

  3. #3
    SitePoint Zealot
    Join Date
    Sep 2010
    Posts
    131
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What happens if I want to use a decimal # that should not be truncated?

  4. #4
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,068
    Mentioned
    153 Post(s)
    Tagged
    2 Thread(s)
    parseInt will truncate it, use parseFloat instead
    Rémon - Hosting Advisor

    SitePoint forums will switch to Discourse soon! Make sure you're ready for it!

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy

  5. #5
    Non-Member Kalon's Avatar
    Join Date
    Aug 2010
    Location
    At my computer
    Posts
    2,012
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    another option is to use the javascript Number Class
    Last edited by Kalon; Sep 22, 2010 at 02:19. Reason: answer already posted

  6. #6
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,810
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    The simplest way is:

    Code:
    var m=+(window.document.myform.mo.value);
    var b=m+24
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">


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
  •