C++ standard guarantee us that we can only safely round-trip decimal values with up to
for double
value std::numeric_limits<double>::digits10
.
After reading this post, I'm wondering if for integers values this threshold it extends to std::numeric_limits<double>::digits10
+1
Asked
Active
Viewed 662 times
4

Community
- 1
- 1

Guillaume Paris
- 10,303
- 14
- 70
- 145
-
The C++ standard and IEEE 754 are unrelated. – n. m. could be an AI Jan 17 '14 at 09:46
-
2@n.m. Note entirely. C++ defines `std::numeric_limits
::is_iec559` (or something like that) which tells if the implementation is complying with IEEE 754. If that's true, then it's certainly valid to ask how to get C++ operators to generate 754 operations which are suitable to a particular purpose. – Potatoswatter Jan 17 '14 at 10:04 -
4std::numeric_limits
::digits10+1 is 16, and you can't round-trip all 16-digit integers (e.g., 9007199254740993 comes back as 9007199254740992). – Rick Regan Jan 17 '14 at 14:11 -
3@RickRegan: You should enter that as an answer. (With an additional qualification that the counterexample is using IEEE-754 64-bit binary floating-point for the `double` type.) – Eric Postpischil Jan 17 '14 at 17:39
1 Answers
3
std::numeric_limits::digits10 is 15 because only values that are 15 digits or less are guaranteed to round-trip from decimal to double-precision and back. Some 16-digit values will round-trip, but not all of them. In the case of integers, only those <= 2^53 = 9007199254740992 are guaranteed to round-trip (because they are represented exactly). 9007199254740993, for example, comes back as 9007199254740992.

Rick Regan
- 3,407
- 22
- 28
-
1Note that only the odd numbers have problems, even numbers are OK until you get to 18014398509481984. – Mark Ransom Jan 18 '14 at 03:18
-
@MarkRansom Yes, that's a much better way to put it. That sounds less mysterious than "some 16-digit values will round-trip, but not all of them". – Rick Regan Jan 18 '14 at 03:53