Skip to content

Commit 9229bd5

Browse files
Emitter: produce string with trailing '.0' for floating point value with only integral part
For example the number 1.0 will be converted to "1.0" instead of "1". This allows to keep the correct type information when parsing back the YAML. This patch is equivalent of jbeder#1377 but for the 0.8.0 version of yaml-cpp.
1 parent f732014 commit 9229bd5

File tree

2 files changed

+19
-7
lines changed

2 files changed

+19
-7
lines changed

include/yaml-cpp/emitter.h

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -162,25 +162,32 @@ inline Emitter& Emitter::WriteStreamable(T value) {
162162

163163
bool special = false;
164164
if (std::is_floating_point<T>::value) {
165+
special = true;
165166
if ((std::numeric_limits<T>::has_quiet_NaN ||
166167
std::numeric_limits<T>::has_signaling_NaN) &&
167168
std::isnan(value)) {
168-
special = true;
169-
stream << ".nan";
169+
m_stream << ".nan";
170170
} else if (std::numeric_limits<T>::has_infinity && std::isinf(value)) {
171-
special = true;
172171
if (std::signbit(value)) {
173-
stream << "-.inf";
172+
m_stream << "-.inf";
174173
} else {
175-
stream << ".inf";
174+
m_stream << ".inf";
176175
}
176+
} else {
177+
stream << value;
178+
std::string result = stream.str();
179+
if (result.find('.') == std::string::npos &&
180+
result.find('e') == std::string::npos) {
181+
result += ".0";
182+
}
183+
m_stream << result;
177184
}
178185
}
179186

180187
if (!special) {
181188
stream << value;
189+
m_stream << stream.str();
182190
}
183-
m_stream << stream.str();
184191

185192
StartedScalar();
186193

test/integration/emitter_test.cpp

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,12 +101,17 @@ TEST_F(EmitterTest, NumberPrecision) {
101101
out.SetFloatPrecision(3);
102102
out.SetDoublePrecision(2);
103103
out << BeginSeq;
104+
out << 1.0f;
104105
out << 3.1425926f;
106+
out << 0.0;
107+
out << 1.0;
105108
out << 53.5893;
106109
out << 2384626.4338;
110+
out << 1999926.4338;
111+
out << 9999926.4338;
107112
out << EndSeq;
108113

109-
ExpectEmit("- 3.14\n- 54\n- 2.4e+06");
114+
ExpectEmit("- 1.0\n- 3.14\n- 0.0\n- 1.0\n- 54.0\n- 2.4e+06\n- 2e+06\n- 1e+07");
110115
}
111116

112117
TEST_F(EmitterTest, SimpleSeq) {

0 commit comments

Comments
 (0)