how to find size of a float

Feb 21, 2011 at 5:48pm
how to find size of a float?

eg
size(123.456)=6
size(12.10)=4
size(1234)=4
size(0.1212)=4
Feb 21, 2011 at 6:21pm
You can't get the number of decimal digits of a float because they are not stored as decimal digits.
A number that can be represented with a finite number of fractional decimal digits may require infinite binary digits so the value of something like 123.456 may be stored as an approximation of that value, not with the value itself.
Feb 21, 2011 at 6:46pm
couldn't you use stringstreams to find the number of digits Bazzy? Numbers like 0.33333333333333.... would cause a problem of course so you'd need to set some upper limit with setprecision. Given that you knew that the initial floats were reasonable values though, I think it'd work.

Of course I can't be sure the OP would know this.
Feb 21, 2011 at 6:50pm
This does exactly that:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    float x;
    cout << "x="; cin >>x;

    stringstream ss (stringstream::in | stringstream::out);

    ss << x;
    string size = ss.str();

    cout << size.length() -1 ;  
}
Last edited on Feb 21, 2011 at 6:54pm
Feb 21, 2011 at 7:28pm
No, it doesn't.

According to OP, size of 0.1212 is 4. Your program will output 5 since it will count the leading zero.

Furthermore, I don't understand the logic in size 12.10 being 4. Why is the trailing zero being counted?
Why isn't the value 12.100 (so the length is 5)?
Feb 21, 2011 at 11:54pm
No, it doesn't


x=12.12121
6

Topic archived. No new replies allowed.