Use std::stringstream instead of snprintf() for double->string conversion

`snprintf()` will use the current `LC_NUMERIC` locale
for converting a double to a string,
which will use a `,` instead of a `.` in some locales (e.g. de_DE).
`std::stringstream` allows setting the locale to `"C"` to always get a `.`.
This occurs only for that `stringstream` instance; no global is
altered.
This commit is contained in:
Steffen Kieß 2014-07-02 13:31:15 +02:00 committed by Christopher Dunn
parent 06dcb1fc89
commit b8aaa03367

View File

@ -63,22 +63,15 @@ std::string valueToString(UInt value) {
#endif // # if defined(JSON_HAS_INT64)
std::string valueToString(double value) {
// Allocate a buffer that is more than large enough to store the 16 digits of
// precision requested below.
char buffer[32];
// Print into the buffer. We need not request the alternative representation
// that always has a decimal point because JSON doesn't distingish the
// concepts of reals and integers.
#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) // Use secure version with
// visual studio 2005 to
// avoid warning.
sprintf_s(buffer, sizeof(buffer), "%.16g", value);
#else
snprintf(buffer, sizeof(buffer), "%.16g", value);
#endif
return buffer;
// We need not request the alternative representation
// that always has a decimal point because JSON doesn't distingish the
// concepts of reals and integers.
std::stringstream str;
// Set locale to "C" to always get a '.' instead of a ','
str.imbue(std::locale::classic());
str.precision(16);
str << value;
return str.str();
}
std::string valueToString(bool value) { return value ? "true" : "false"; }