### 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:

 ``12345678910111213141516`` `````` #include "stdafx.h" #include #include using namespace std; int main() { double nmbr; cin>>nmbr; cout<
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 ?

code:

 ``12345678910111213141516171819202122232425262728293031`` ``````#include "stdafx.h" #include #include #include 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
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
 ``1234567`` ``````double x = 23.1111; x -= (int)x; int y = 0; for(;x-(int)x > 0 + 1e-10;++y,x*=10){} cout<

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

 ``1234`` ``````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.