Skip to content

Instantly share code, notes, and snippets.

@goshki
Created September 7, 2010 13:01
Show Gist options
  • Save goshki/568285 to your computer and use it in GitHub Desktop.
Save goshki/568285 to your computer and use it in GitHub Desktop.
JavaScript function to return a decimal digit at specific position (0-indexed, from the end) of a given number.
/**
* Returns a given power of ten (10 ^ 0 = 1, 10 ^ 1 = 10, 10 ^ 2 = 100, etc.).
*/
function powerOfTen( power ) {
var result = 1;
for ( i = 0; i < power; i++ ) {
result *= 10;
}
return result;
}
/**
* Returns a digit at specific position (0-indexed, from the end) of a given number. For example:
* - a first digit of 5 is 5
* - a first digit of 15 is 5
* - a second digit of 15 is 1
* - a third digit of 215 is 2
* - a third digit of 15 is 0 (it does not exist)
* - a second digit of 5 is 0 (does not exist either)
*/
function getDigitAtPosition( integer, position ) {
var positionInBase10 = powerOfTen( position );
var nextPositionInBase10 = powerOfTen( position + 1 );
return ( integer % nextPositionInBase10 - integer % positionInBase10 ) / positionInBase10;
}
alert( getDigitAtPosition( 1234, -1 ) == 0 );
alert( getDigitAtPosition( 1234, 0 ) == 4 );
alert( getDigitAtPosition( 1234, 1 ) == 3 );
alert( getDigitAtPosition( 1234, 2 ) == 2 );
alert( getDigitAtPosition( 1234, 3 ) == 1 );
alert( getDigitAtPosition( 1234, 4 ) == 0 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment