What’s the best, platform-independent way to obtain the maximum value that can be stored in a float
in C++?
Asked
Active
Viewed 3,813 times
8

mskfisher
- 3,291
- 4
- 35
- 48

Tony the Pony
- 40,327
- 71
- 187
- 281
5 Answers
9
// numeric_limits example
#include <iostream>
#include <limits>
using namespace std;
int main () {
cout << "Minimum value for float: " << numeric_limits<float>::min() << endl;
cout << "Maximum value for float: " << numeric_limits<float>::max() << endl;
cout << "Minimum value for double: " << numeric_limits<double>::min() << endl;
cout << "Maximum value for double: " << numeric_limits<double>::max() << endl;
return 0;
}

Todd
- 2,321
- 14
- 11
-
2It should be noted that the calls to min() for floating-point types return the minimum positive value, not the minimum value. There's a big difference. – James McNellis Oct 14 '09 at 18:44
1
In C++ you can use the std::numeric_limits
class to get this sort of information.
If has_infinity
is true
(which will be true for basically all platforms nowadays), then you can use infinitity
to get the value which is greater than or equal to all other values (except NaNs). Similarly, its negation will give a negative infinity, and be less than or equal to all other values (except NaNs again).
If you want finite values, then you can use min
/max
(which will be less than or equal to/greater than or equal to all other finite values).

Simon Byrne
- 7,694
- 1
- 26
- 50
-1
#include <float.h>
then use FLT_MAX

Nick Dandoulakis
- 42,588
- 16
- 104
- 136

tster
- 17,883
- 5
- 53
- 72
-
standard library headers are best imported without the extension . See this SO question http://stackoverflow.com/questions/441568/when-can-you-omit-the-file-extension-in-an-include-directive for an overview. – Francesco Sep 27 '09 at 19:54