Code of the day: C, Get the Digits from a Number

Today’s Code of the Day is about how to find the digit of a number at a given position. I decided to go with the C / C++ programming languages to time, but you can easily translate the algorithms to other languages.

C Code.

#include 
#include 

// Function: getDigitFromNum returns a digit at a given index of a integer.
// Goes from right to left with the starting index of 0.
int getDigitFromNum( int num, int digit ){
    num /= pow( 10, digit );
    return num % 10;
}
// Function: getDigitFromDec returns a digit at a given index of a double.
// Goes from left to right with the starting index of 0.
int getDigitFromDec( double dec, int digit ){
    dec *= pow( 10, digit );
    return (int)dec % 10;
}
// Function: getDigitFromNum returns the decimal values of a double.
double getDecimals( double dec ){
    return dec - (int)dec;
}

Example:
Input File

// Programmed by Larry Battle, bateru.com/news
// Date: April 26, 2011
// Purpose: To demonstrate how to get a digit by a position index.
#include 
#include 

int getDigitFromNum( int num, int digit ){
    num /= pow( 10, digit );
    return num % 10;
}
int getDigitFromDec( double dec, int digit ){
    dec *= pow( 10, digit );
    return ((int)dec) % 10;
}
double getDecimals( double dec ){
    return dec - (int)dec;
}

void main(){
    double dec = 1234.56789;
    printf( "\n%d", getDigitFromNum( (int)dec, 0 ));
    printf( "\n%d", getDigitFromDec( dec, 2 ));
    printf( "\n%f", getDecimals( dec ));
}

Output:

4
6
0.567890
Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

Share
Published by
Larry Battle
Tags: C / C++math

Recent Posts

What really is Data Science? Told by a Data Scientist

What REALLY is Data Science? Told by a Data Scientist - By Joma Tech

7 years ago

Video: How Water Towers Work

How Water Towers Work - Practical Engineering

7 years ago

Dev Tip: Simple tips to improve code reviews

Writing perfect code is a challenging process. That's where code reviews come in to help…

7 years ago

Video: How AI will change the 3d industry

"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"

7 years ago

Best Software Presentation for 2018

"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"

7 years ago

Dev Video: A Few Linux Shell Tips

My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…

7 years ago