how to find size of a float

how to find size of a float?

eg
size(123.456)=6
size(12.10)=4
size(1234)=4
size(0.1212)=4
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.
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.
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
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)?
No, it doesn't


x=12.12121
6

Topic archived. No new replies allowed.