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

2 Answers

0 votes
#include <iostream>
#include <sstream>
#include <string>

int get_first_digit(double value)
{
    std::ostringstream os;
    os << value;

    std::string s = os.str();
    return s[0] - '0';
}

int main()
{
    double d = 23.871;

    int first_digit = get_first_digit(d);

    std::cout << first_digit;  
}


/*
run:

2

*/

 



answered Aug 24, 2019 by avibootz
edited Sep 15 by avibootz
0 votes
#include <iostream>
#include <cmath>
 
int first_digit(int n) { 
    int digits = (int)log10(n); 
   
    n = (int)(n / pow(10, digits)); 
   
    return n; 
} 
 
int main() 
{ 
    float f = 476.287152; 
      
    std::cout << first_digit((int)f);
}   
        
  
        
/*
run:
 
4
      
*/

 



answered Aug 27, 2019 by avibootz
edited Sep 15 by avibootz
...