|
43 | 43 | #include <cmath>
|
44 | 44 | #include <cstring>
|
45 | 45 | #include <string>
|
| 46 | +#include <charconv> |
| 47 | +#include <system_error> |
46 | 48 |
|
47 | 49 | #include "mp/nl-writer2.h"
|
48 | 50 | #include "mp/nl-writer2.hpp"
|
@@ -152,9 +154,20 @@ int TextFormatter::apr(File& f, const char *fmt, ...)
|
152 | 154 | while (*fmt++ != 'g');
|
153 | 155 | case 'g':
|
154 | 156 | x = va_arg(ap, double);
|
155 |
| -#ifdef NL_LIB_USE_SPRINTF |
156 |
| - snprintf(s = buf, |
157 |
| - sizeof(buf), "%.*g", output_prec, x); |
| 157 | +#define NL_LIB_USE_TO_CHARS |
| 158 | +#ifdef NL_LIB_USE_TO_CHARS |
| 159 | + std::to_chars_result res; |
| 160 | + if (output_prec <= 0) // shortest representation |
| 161 | + res = std::to_chars(s = buf, buf+sizeof(buf)-1, x); |
| 162 | + else // 24 characters enough IEEE 754 |
| 163 | + res = std::to_chars(s = buf, buf+sizeof(buf)-1, x, |
| 164 | + std::chars_format::general, |
| 165 | + output_prec); |
| 166 | + if (res.ec == std::errc()) // OK |
| 167 | + *res.ptr = '\0'; |
| 168 | + else |
| 169 | + Utils().myexit("aprintf / to_chars bug: " + |
| 170 | + std::make_error_code(res.ec).message()); |
158 | 171 | #elif NL_LIB_USE_OWN_GFMT
|
159 | 172 | NL_LIB_GFMT::gfmt(s = buf, sizeof(buf), x, output_prec);
|
160 | 173 | #else
|
@@ -306,6 +319,8 @@ apr(File& f, const char *fmt, ...)
|
306 | 319 | } // namespace mp
|
307 | 320 |
|
308 | 321 |
|
| 322 | +#ifndef NL_LIB_USE_TO_CHARS |
| 323 | + |
309 | 324 | extern "C" {
|
310 | 325 | char *
|
311 | 326 | dtoa_r_dmgay(double dd, int mode, int ndigits,
|
@@ -459,3 +474,5 @@ void gfmt(char *b, size_t sz, double x, int prec) {
|
459 | 474 | }
|
460 | 475 |
|
461 | 476 | } // namespace NL_LIB_GFMT
|
| 477 | + |
| 478 | +#endif // NL_LIB_USE_TO_CHARS |
0 commit comments