### Hi, quick question about displaying a value.

Hello, I need help displaying just the first digit of a number. I thought the code was setprecision but apparently that is just for decimals. For example I have a variable that equals 1430 but I only want to display the first digit, the 1. Anyone know the command or any simple way to do this? Thank you.
And to add on to that, I just cant divide it by 1000 and use set point to eliminate the decimal because it has to work for several different numbers. Like just the '5' in 56 and just the '4' in 4829. All I need is to find this solution and then I can finish the problem. THanks again
Try to use std::to_string. For example

`std::cout << std::to_string( 1436 )[0] << std::endl;`
You would use integer division by its largest digit, e.g.
 ``12`` ``````int num = 4587 //large number int firstdigit = 4587 / 1000 //divide by the largest power of 10 ``````

integer division does not round, so dividing by a power of 10 will give you the first digit.

EDIT: if you dont know the exact value of the digit you could use this method:

 ``1234567891011121314151617181920212223242526272829`` ``````#include #include using namespace std; int numDigits(int number) { int digits = 0; //count number of digits while(number) //while number is valid { number /= 10; //integer division digits++; //add one onto digits } return digits; //return digits } int main() { int NUM; cout << "Enter a number: "; cin >> NUM; cout << "First digit is: " << NUM / (int)pow(10,numDigits(NUM) -1); //Heres a less complex way to write that line: //int digits = numDigits(NUM); //int FirstDigit = pow(10,digits-1) - ex 4 digits, means 10 ^ 3 or 1000 //note** pow returns a double, so make sure to cast it as an integer //cout << FirstDigit; } ``````
Last edited on
sorry Need4Sleep i just said that i have to run the same program for multiple variables that can be less then 1000 or over 10,000 and i wont be able to modify the program inbetween