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

2 Answers

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

using namespace std;


int main() 
{
    double d = 23.871;

    ostringstream os;
    
    os << d;
    
    string s = os.str();

    int first_digit = s[0] - '0';
    
    cout << first_digit;
}




/*
run:

2

*/

 



answered Aug 24, 2019 by avibootz
0 votes
#include <iostream>
#include <cmath>

using namespace std;

int first_digit(int n) { 
    int digits = (int)log10(n); 
  
    n = (int)(n / pow(10, digits)); 
  
    return n; 
} 

int main() 
{ 
    float f = 476.287152; 
     
    cout << first_digit((int)f);

    return 0; 
}   
       
       
 
       
/*
run:

4
     
*/

 



answered Aug 27, 2019 by avibootz

Related questions

2 answers 205 views
3 answers 272 views
1 answer 230 views
...