how to find the no of digits after decimal point exactly

//c++ code

int nocheck1(float e)
{
float q;
int count1=0;
q=e;
while(q!=(int(q)))
{
count1++;
q=q*10;

}
//cout<<count1;
return count1;
}


this code will provide a count to a maximum of 6 digits after dec point..not any more...what is the alternative to this problem in c++??


Last edited on
Floats have 23-bit mantissas (~6.9 decimal digits), so 6 decimal digits is roughly all you can expect to get.
Then what's the way to print a floating point no exactly as it is?
Do you mean mathematical float, or computer floating point type? The latter have discrete values with limited precision and can thus hardly ever be "exact".
There is no primitive type in C++ which can hold a number exactly. If you need exact math you should seek out a dedicated library, but generally 64-bit double is sufficient for most purposes. (Except with money, you should never use a floating point type)
Last edited on
Then what's the way to print a floating point no exactly as it is?
Exactly?
1
2
float f = foo();
std::cout << *(std::uint32_t *)&f;
This prints an exact representation of the value of f. The output may not necessarily be useful or portable to other computers.
I believe there is only one better method to get the number of decimal digits in a float than the one you're currently using.
A float is simply a fixed-length sum of powers of two. All powers of two have finite (i.e. non-repeating) decimal representations. E.g. 2^-23 is 0.00000011920928955078125. If you convert the terms of the sum to decimal representations and then add them using arbitrary precision arithmetic, you'll get the exact decimal representation of the floating point number. After this, you just need to count. See https://en.wikipedia.org/wiki/Single-precision_floating-point_format

Any C++ numeric type holds an exact value. The problems arise when you want to convert from a real number to float and back to a real number, or when you apply real-valued functions (or approximations thereof, as are the functions in <cmath>) to floats.
Last edited on
I'll just leave this here: https://gist.github.com/Helios-vmg/abd9ef1153c5d43d7a29

This was actually fun to write. This takes input from the user, converts it to a floating point type (works with both float and double), then prints out the exact decimal representation corresponding to that floating point representation. Example output:
0.1
0.1000000000000000055511151231257827021181583404541015625 - 55
3.14
3.140000000000000124344978758017532527446746826171875 - 51
0.25
0.25 - 2
9007199254740991
9007199254740991 - 0
9007199254740992
9007199254740992 - 0
9007199254740993
9007199254740992 - 0
9007199254740994
9007199254740994 - 0
Topic archived. No new replies allowed.