Get first number

Discussion in 'JavaScript' started by Zynex, Feb 26, 2007.

  1. #1
    I was wondering if it is possible to get the first number of a bigger number. For instance when a variable is 2674, that I can store the first number (in this case "2") and store it in another variable.

    Thanx in advance!,

    Zynex
     
    Zynex, Feb 26, 2007 IP
  2. Roman

    Roman Buffalo Tamerâ„¢

    Messages:
    6,217
    Likes Received:
    592
    Best Answers:
    0
    Trophy Points:
    310
    #2
    Just keep dividing it by 10 while it's greater than ten and then store the result as an integer.
     
    Roman, Feb 26, 2007 IP
  3. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #3
    
    
    var num = 2674;
    
    var first = num.toString().substr(0, 1);
    
    Code (javascript):
    EDIT:

    Or:
    
    var first = num.toString()[0];
    
    Code (javascript):
     
    nico_swd, Feb 26, 2007 IP
  4. designcode

    designcode Well-Known Member

    Messages:
    738
    Likes Received:
    37
    Best Answers:
    0
    Trophy Points:
    118
    #4
    
    <script type="text/javascript">
    
    var str="2674"
    var shortStr = str.substring(0,1);
    
    </script>
    
    Code (markup):
    Try above code. but keep it mind, var str should be string.
     
    designcode, Feb 26, 2007 IP