avoid to use sprintf format "%.17g"

This commit is contained in:
Stefano Fiorentino 2016-02-12 12:47:58 +01:00
parent ee2ef58555
commit c0a7cfa798

View File

@ -8,6 +8,7 @@
#include "json_tool.h" #include "json_tool.h"
#endif // if !defined(JSON_IS_AMALGAMATION) #endif // if !defined(JSON_IS_AMALGAMATION)
#include <iomanip> #include <iomanip>
#include <iostream>
#include <memory> #include <memory>
#include <sstream> #include <sstream>
#include <utility> #include <utility>
@ -141,18 +142,15 @@ std::string valueToString(double value, bool useSpecialFloats, unsigned int prec
char buffer[32]; char buffer[32];
int len = -1; int len = -1;
unsigned int length = (value==0.0)?(unsigned int)1:(unsigned int)(std::floor(std::log10(std::abs(value)))+1); std::stringstream value_ss;
if (length<1) length=1; value_ss << std::setprecision( 15 ) << value;
if (length>precision-1) length = precision-1; std::string value_str = value_ss.str();
char formatString[6];
sprintf(formatString, "%%.%dg", precision-length);
// Print into the buffer. We need not request the alternative representation // Print into the buffer. We need not request the alternative representation
// that always has a decimal point because JSON doesn't distingish the // that always has a decimal point because JSON doesn't distingish the
// concepts of reals and integers. // concepts of reals and integers.
if (isfinite(value)) { if (isfinite(value)) {
len = snprintf(buffer, sizeof(buffer), formatString, value); len = snprintf(buffer, sizeof(buffer), value_str.c_str());
} else { } else {
// IEEE standard states that NaN values will not compare to themselves // IEEE standard states that NaN values will not compare to themselves
if (value != value) { if (value != value) {