get the amount of decimals of a number.

Hello i have a program in which a user inputs a decimal number and then my program should tell how many numbers are behind the coma. so for example if the user enters 358.5492 then the program should output 4. I tried this very short code but it doesn't work and i have no idea what to try next. could someone help me out please.

code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
	double nmbr;
	cin>>nmbr;
	cout<<nmbr.precision();

	system("pause");
	return 0;
}
Last edited on
Right i just thought of something when i posted this and now i have this as code but it only accept like 8 digits in total the others aren't counted somehow. so for example if i input 5268.2668 it rounds it untill there are 7 characters so that would become 5268.27 and it tells me there are only 2 digits behind the coma. same happens if i enter 358.549256 and it tells me there are only 3 numbers behind the coma. so i don't see what's going on.
could someone tell me what i could do to avoid this from happening ?

thanks in advance

code:

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
30
31
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <sstream>
using namespace std;

int main()
{
	float nmbr;
	cin>>nmbr;
	ostringstream strs;
	strs << nmbr;
	string str = strs.str();
	int count=0;
	bool start=false;
	for (int k=0;k<str.length();k++) {
		if (start==true) {
			//cout<<str.at(k)<<endl;
			count++;
		}
		if (str.at(k)==46) {
			start=true;
		}
	}
	cout<<count<<endl;
	
	
	system("pause");
	return 0;
}
a real easy way to do this would be to read the number in as a string so you can parse it easily and count the decimals easily and then if you need to use it as a number just use atof() to convert it into a float
1
2
3
4
5
6
7
double x = 23.1111;
x -= (int)x;

int y = 0;

for(;x-(int)x > 0 + 1e-10;++y,x*=10){}
cout<<x<<endl<<y<<endl;


To optimize a little bit, to make sure x doesn't get out of range.

1
2
3
4
double x = 23.1111;
x -= (int)x;
unsigned int y = 0;
for(;x > 0 + 1e-10;++y,x*=10,x-=(int)x){}
Last edited on
Topic archived. No new replies allowed.