命名空间
变体
操作

std::numeric_limits<T>::digits10

来自 cppreference.cn
 
 
 
 
 
static const int digits10;
(直到 C++11)
static constexpr int digits10;
(自 C++11 起)

std::numeric_limits<T>::digits10 的值是类型 T 可以无损表示的十进制数字位数,也就是说,任何具有这么多有效十进制数字的数字都可以转换为 T 类型的值,然后再转换回十进制形式,而不会因舍入或溢出而发生变化。对于基数-radix 类型,它是 digits() 的值(对于浮点类型,是 digits - 1 )乘以 log10(radix) 并向下舍入。

[edit] 标准特化

T std::numeric_limits<T>::digits10 的值
/* 非特化 */ 0
bool 0
char std::numeric_limits<char>::digits * std::log10(2)
signed char std::numeric_limits<signed char>::digits * std::log10(2)
unsigned char std::numeric_limits<unsigned char>::digits * std::log10(2)
wchar_t std::numeric_limits<wchar_t>::digits * std::log10(2)
char8_t (自 C++20 起) std::numeric_limits<char8_t>::digits * std::log10(2)
char16_t (自 C++11 起) std::numeric_limits<char16_t>::digits * std::log10(2)
char32_t (自 C++11 起) std::numeric_limits<char32_t>::digits * std::log10(2)
short std::numeric_limits<short>::digits * std::log10(2)
unsigned short std::numeric_limits<unsigned short>::digits * std::log10(2)
int std::numeric_limits<int>::digits * std::log10(2)
unsigned int std::numeric_limits<unsigned int>::digits * std::log10(2)
long std::numeric_limits<long>::digits * std::log10(2)
unsigned long std::numeric_limits<unsigned long>::digits * std::log10(2)
long long (自 C++11 起) std::numeric_limits<long long>::digits * std::log10(2)
unsigned long long (自 C++11 起) std::numeric_limits<unsigned long long>::digits * std::log10(2)
float FLT_DIG (6 对于 IEEE float)
double DBL_DIG (15 对于 IEEE double)
long double LDBL_DIG (18 对于 80 位 Intel long double; 33 对于 IEEE 四精度)

[edit] 示例

一个 8 位二进制类型可以精确表示任何两位十进制数,但 3 位十进制数 256..999 无法表示。 8 位类型的 digits10 值为 2 (8 * std::log10(2) 为 2.41)

标准的 32 位 IEEE 754 浮点类型具有 24 位小数部分(23 位写入,一位隐含),这可能表明它可以表示 7 位十进制数 (24 * std::log10(2) 为 7.22),但相对舍入误差是不均匀的,并且一些具有 7 位十进制数字的浮点值无法在转换为 32 位浮点数并返回后幸存:最小的正例是 8.589973e9,在往返后变为 8.589974e9。这些舍入误差不能超过表示中的一位,并且 digits10 的计算公式为 (24 - 1) * std::log10(2),即 6.92。向下舍入得到值 6。

同样,16 位数字字符串 9007199254740993 无法在 text->double->text 往返中幸存,变为 9007199254740992:64 位 IEEE 754 类型 double 仅保证 15 位十进制数字的往返。

[edit] 参见

[static] (C++11)
区分此类型所有值所需的十进制数字位数
(public static member constant) [编辑]
[static]
给定类型的表示形式使用的基数或整数基
(public static member constant) [编辑]
[static]
可以无损表示的 radix 位数
(public static member constant) [编辑]
比作为有效规范化浮点值的最小负基数幂大 1
(public static member constant) [编辑]
比作为有效有限浮点值的最大整数基数幂大 1
(public static member constant) [编辑]