Jonathan Mee Jonathan Mee - 1 year ago 75
C++ Question

What Are the Maximum Number of Base-10 Digits in the Integral Part of a Floating Point Number

I want to know if there is something in the standard, like a

or something in
which would tell me the maximum number of base-10 digits in the integral part of a floating point type.

For example, if I have some floating point type the largest value of which is: 1234.567. I'd like something defined in the standard that would tell me 4 for that type.

Is there an option to me doing this?

template <typename T>
constexpr auto integral_digits10 = static_cast<int>(log10(numeric_limits<T>::max())) + 1;

Answer Source

The value that you are looking for is max_exponent10 which:

Is the largest positive number n such that 10n is a representable finite value of the floating-point type

Because of this relationship:

log10x = n
10n = x

Your calculation is doing, is finding n the way the first equation works:


The definition of max_exponent10 is explaining that it is using a 10n + 1 would be larger than numeric_limits<T>::max() but 10n is less than or equal to numeric_limits<T>::max(). So numeric_limits<T>::max_exponent10 is what you're looking for.

Note that you will still need the + 1 as in your example, to account for the 1's place. (Because log101 = 0) So your the number of 10-based digits required to represent numeric_limits<T>::max() will be:

numeric_limits<T>::max_exponent10 + 1

If you feel like validating that by hand you can check here:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download