What should the output of to_chars(123456789.0, chars_format::general) be? #1487
-
Current implementation:
My understanding is that for general shortest, the output is in the same format as
Question 2: should the output of |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I found the Standardese here to be unclear, and explained my reasoning on Reddit last year. The central question is indeed what My interpretation was that The advantage of this Here's an example that shows why I believe that the current implementation captures the Standard's "style of
#include <charconv>
#include <cstdio>
#include <cstdlib>
#include <iterator>
#include <system_error>
using namespace std;
void test_general(const double dbl) {
char buf[24]; // worst case "-1.2345678901234567e-100"
const auto result = to_chars(buf, end(buf), dbl, chars_format::general);
if (result.ec != errc{}) {
puts("FAIL");
exit(EXIT_FAILURE);
}
printf("%-11g | %.*s\n", dbl, static_cast<int>(result.ptr - buf), buf);
}
int main() {
printf("printf %%g | to_chars general\n");
test_general(0.123456789);
test_general(0.12345678);
test_general(0.1234567);
test_general(0.123456);
test_general(0.12345);
test_general(0.1234);
test_general(0.123);
test_general(0.12);
test_general(0.1);
test_general(1.0);
test_general(12.0);
test_general(123.0);
test_general(1234.0);
test_general(12345.0);
test_general(123456.0);
test_general(1234567.0);
test_general(12345678.0);
test_general(123456789.0);
printf("\n");
printf("printf %%g | to_chars general\n");
test_general(1e-9);
test_general(1e-8);
test_general(1e-7);
test_general(1e-6);
test_general(1e-5);
test_general(1e-4);
test_general(1e-3);
test_general(1e-2);
test_general(1e-1);
test_general(1e0);
test_general(1e1);
test_general(1e2);
test_general(1e3);
test_general(1e4);
test_general(1e5);
test_general(1e6);
test_general(1e7);
test_general(1e8);
test_general(1e9);
}
So my answer is: This was intentional, although I will be interested to see what libstdc++'s independent implementation does (I saw that @jwakely is using Ryu, but this logic is outside Ryu itself). I would also prefer for the Standardese to say something clearer here. One of @jwakely's Proposed Resolutions for LWG-3456 makes the |
Beta Was this translation helpful? Give feedback.
I found the Standardese here to be unclear, and explained my reasoning on Reddit last year. The central question is indeed what
P
should be, and the confusion is caused by the Standardese being split between C and C++. Your Question 2 about10000
is essentially the same as my1700
scenario.My interpretation was that
printf
's "style" is used to decide between fixed and scientific, and I considered theP = 6
default to be applicable, because theprecision
was indeed omitted in theto_chars
call. But the actual number of digits being printed is controlled by the C++ Standardese. This is indeed a different interpretation than behaving like%.*g
with a magically varying runtime precision - th…