PDA

View Full Version : Getting first digits in a number

jomak73
07-19-2010, 06:59 PM
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!!

RandomUser531
07-19-2010, 07:43 PM
If the number has only one digit:
The first function returns 0.
The second function returns the number unchanged.

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

mrhoo
07-19-2010, 07:58 PM
Given any double or triple digit number (N)

N=Math.floor(N/10)

Old Pedant
07-19-2010, 08:30 PM
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:

Math.floor( -173.20 / 10 ) ) ==>> -18

but we'll presumably ignore that?)