SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Jul 2002
    Posts
    95
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    String to number conversion. How?

    I want to convert a string to a number in JavaScript... How can I do that?


    For example: a page that puts a and b together and has window.prompt to define a and b. But when a user sets a to lets say 3 (a = window.prompt("a=?", "3"), this is not a number 3 but a string "3" and therefore cannot be used in calculations.
    So how can I convert this "3" string (or any other "number" string to a number?)

  2. #2
    Grumpy Mole Man Skunk's Avatar
    Join Date
    Jan 2001
    Location
    Lawrence, Kansas
    Posts
    2,067
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Use the parseInt function:
    Code:
    number = parseInt("3");

  3. #3
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Right on skunk, or if you have a decimal (floating point) you need this:
    Code:
    var decimalStr = "3.2";
    decimal = parseFloat(decimalStr);
    Conversely, to switch number variable to string, just concatentate an empty string
    Code:
    var int = 3;
    var intStr = int + "";
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  4. #4
    Perl/Mason Guru Flawless_koder's Avatar
    Join Date
    Feb 2002
    Location
    Gatwick, UK
    Posts
    1,206
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You can also eval - if the circumstances are right - to go both ways.

    Flawless
    ---=| If you're going to buy a pet - get a Shetland Giraffe |=---


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
  •