std::numeric_limits<T>::max_digits10

来自cppreference.com
 
 
 
 
 
static constexpr int max_digits10
(C++11 起)

std::numeric_limits<T>::max_digits10 的值是唯一地表示类型 T 的所有值所需的以 10 为底的位数,序列化/反序列化到文本需要用到该值。此常量对所有浮点数类型都有意义。

标准特化

Tstd::numeric_limits<T>::max_digits10 的值
/* 未特化 */0
bool0
char0
signed char0
unsigned char0
wchar_t0
char8_t (C++20 起)0
char16_t0
char32_t0
short0
unsigned short0
int0
unsigned int0
long0
unsigned long0
long long0
unsigned long long0
floatFLT_DECIMAL_DIGstd::ceil(std::numeric_limits<float>::digits * std::log10(2) + 1)
doubleDBL_DECIMAL_DIGstd::ceil(std::numeric_limits<double>::digits * std::log10(2) + 1)
long doubleDECIMAL_DIGLDBL_DECIMAL_DIGstd::ceil(std::numeric_limits<long double>::digits * std::log10(2) + 1)

注解

与多数数学运算不同,只要用至少 max_digits10(对于 float9,对于 double17)位,那么从浮点数转换到文本并转换回来是准确 的:保证产生同一浮点数,即使中间文本表示不准确。但以小数点记法,可能需要超过一百个十进制数字来表示 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 是 " << digits10 << " 位\n"
                 "   max_digits10 是 " << max_digits10 << " 位\n"
                 "submax_digits10 是 " << submax_digits10 << " 位\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 是 6 位
   max_digits10 是 9 位
submax_digits10 是 8 位
 
   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

参阅

[静态]
给定类型的表示所用的基或整数底
(公开静态成员常量)
[静态]
能无更改地表示的 radix 位数
(公开静态成员常量)
[静态]
能无更改地表示的十进制位数
(公开静态成员常量)
底的该数次幂是合法正规浮点数的最小负数加一
(公开静态成员常量)
底的该数次幂是合法有限浮点数的最大整数加一
(公开静态成员常量)