Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Jul 2010
    Posts
    10
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Getting first digits in a number

    Ooook so this is probably the stupidest question ever. I know in java you can take advantage of a number being an int (not double) and divide by something without getting a remainder. But in javascript you dont declare what kind of variable something is.

    So my problem is: Given any double or triple digit number, how do i get all but the last digit. Like if i have 13, I need to make an int with 1. If it's 103 i need one with 10.

    Thanks!!

  • #2
    New Coder
    Join Date
    Jul 2010
    Posts
    61
    Thanks
    0
    Thanked 21 Times in 21 Posts
    If the number has only one digit:
    The first function returns 0.
    The second function returns the number unchanged.
    Code:
    function getDigits( num )
    {
     var str = Math.round( num ).toString();
       
     return Number( str.substring( 0, str.length - 1 ) );
    }
    
    function getDigits( num )
    {
     var n = Math.round( num ).toString().match( /(\d+)(\d)/ );
       
     return Number( n ? n[ 1 ] : num );
    }

  • #3
    Regular Coder
    Join Date
    Mar 2006
    Posts
    726
    Thanks
    35
    Thanked 132 Times in 123 Posts
    Given any double or triple digit number (N)

    N=Math.floor(N/10)
    Last edited by mrhoo; 07-19-2010 at 08:00 PM.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,155
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Actually, MrHoo's answer works for any number. Just that if the number is less than 10, you will always get 0 as a result. (And of course negative numbers come out strangely:
    Code:
    Math.floor( -173.20 / 10 ) ) ==>> -18
    but we'll presumably ignore that?)
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

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