How to get the first digit of a float number in C

3 Answers

0 votes
#include <stdio.h>

int get_first_digit(float x) {
    while (x >= 9)
        x /= 10;

    return (int)x;
}

int main()
{
    float f = 376.287152;

    int first_digit = get_first_digit(f);

    printf("%d\n", first_digit);  

    return 0;
}


/*
run:
     
3
        
*/

 



answered Aug 27, 2019 by avibootz
edited Sep 15 by avibootz
0 votes
#include <stdio.h>

int get_first_digit(float x) {
    while (x > 10000)
        x /= 1000;

    while (x >= 9)
        x /= 10;

    return (int)x;
}

int main()
{
    float f = 87473734.287152;

    int first_digit = get_first_digit(f);

    printf("%d\n", first_digit);   

    return 0;
}



/*
run:
     
8
        
*/

 



answered Aug 27, 2019 by avibootz
edited Sep 15 by avibootz
0 votes
#include <stdio.h> 
#include <math.h> 
  
int get_first_digit(float f) { 
    int n = (int)f;
    int total_digits_minus_one = (int)log10(n); 
   
    n = (int)(n / pow(10, total_digits_minus_one)); 
   
    return n; 
} 
  
int main() 
{ 
    float f = 576.287152; 
      
    printf("%d\n", get_first_digit(f));
      
    return 0; 
}   
        
  
        
/*
run:
        
5
      
*/

 



answered Aug 27, 2019 by avibootz
edited Aug 31, 2019 by avibootz
...