std::numeric_limits<T>::max_digits10

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

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

目录

[编辑] 标准特化

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_DIGstd::ceil(std::numeric_limits<float>::digits * std::log10(2) + 1)
double DBL_DECIMAL_DIGstd::ceil(std::numeric_limits<double>::digits * std::log10(2) + 1)
long double DECIMAL_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 位数
(公开静态成员常量) [编辑]
[静态]
能无更改地表示的十进制位数
(公开静态成员常量) [编辑]
底的该数次幂是合法正规浮点数的最小负数加一
(公开静态成员常量) [编辑]
底的该数次幂是合法有限浮点数的最大整数加一
(公开静态成员常量) [编辑]