Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

Thread: Getting first digits in a number

1. 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!!

• 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 );
}```

• Given any double or triple digit number (N)

N=Math.floor(N/10)

• 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?)

•

Posting Permissions

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