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.
1
2
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <cmath>
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
my second part of the code or vlads post should answer your question.
thanks
Topic archived. No new replies allowed.