Namespaces
Variants

std::numeric_limits<T>:: max_digits10

From cppreference.net
Utilities library
static constexpr int max_digits10
(自 C++11 起)

std:: numeric_limits < T > :: max_digits10 的值是表示类型 T 所有不同值所需的十进制位数,例如在文本序列化/反序列化过程中所必需的。该常量对所有浮点类型均具有意义。

目录

标准特化

T std:: numeric_limits < T > :: max_digits10 的值
/* 非特化类型 */ 0
bool 0
char 0
signed char 0
unsigned char 0
wchar_t 0
char8_t (C++20 起) 0
char16_t 0
char32_t 0
short 0
unsigned short 0
int 0
unsigned int 0
long 0
unsigned long 0
long long 0
unsigned long long 0
float FLT_DECIMAL_DIG std:: ceil ( std:: numeric_limits < float > :: digits * std:: log10 ( 2 ) + 1 )
double DBL_DECIMAL_DIG std:: ceil ( std:: numeric_limits < double > :: digits * std:: log10 ( 2 ) + 1 )
long double DECIMAL_DIG LDBL_DECIMAL_DIG std:: ceil ( std:: numeric_limits < long double > :: digits * std:: log10 ( 2 ) + 1 )

注释

与大多数数学运算不同,浮点数值到文本的转换及反向转换是 精确 的,只要至少使用了 max_digits10 9 对应 float 17 对应 double ):即使中间文本表示不精确,也能保证生成相同的浮点数值。要使用十进制表示法精确表示 float 的精确值,可能需要超过一百位十进制数字。

示例

#include <cmath>
#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
int main()
{
    float value = 10.0000086;
    constexpr auto digits10 = std::numeric_limits<decltype(value)>::digits10;
    constexpr auto max_digits10 = std::numeric_limits<decltype(value)>::max_digits10;
    constexpr auto submax_digits10 = max_digits10 - 1;
    std::cout << "float:\n"
                 "       digits10 is " << digits10 << " digits\n"
                 "   max_digits10 is " << max_digits10 << " digits\n"
                 "submax_digits10 is " << submax_digits10 << " digits\n\n";
    const auto original_precision = std::cout.precision();
    for (auto i = 0; i < 5; ++i)
    {
        std::cout
            << "   max_digits10: " << std::setprecision(max_digits10) << value << "\n"
               "submax_digits10: " << std::setprecision(submax_digits10) << value
            << "\n\n";
        value = std::nextafter(value, std::numeric_limits<decltype(value)>::max());
    }
    std::cout.precision(original_precision);
}

输出:

float:
       digits10 is 6 digits
   max_digits10 is 9 digits
submax_digits10 is 8 digits
   max_digits10: 10.0000086
submax_digits10: 10.000009
   max_digits10: 10.0000095
submax_digits10: 10.00001
   max_digits10: 10.0000105
submax_digits10: 10.00001
   max_digits10: 10.0000114
submax_digits10: 10.000011
   max_digits10: 10.0000124
submax_digits10: 10.000012

参见

[static]
用于表示给定类型的基数或整数进制
(公开静态成员常量)
[static]
可无更改表示的 radix 进制数字位数
(公开静态成员常量)
[static]
可无更改表示的十进制数字位数
(公开静态成员常量)
最小的负基数幂(该幂是有效的归一化浮点值)加一
(公开静态成员常量)
最大的整数基数幂(该幂是有效的有限浮点值)加一
(公开静态成员常量)