Browse Source

Avoid unnecessary zeros when writing double values to XML or JSON

tags/2021-05-28
ed 6 years ago
parent
commit
3ba771507d
3 changed files with 38 additions and 19 deletions
  1. +6
    -1
      modules/juce_core/javascript/juce_JSON.cpp
  2. +29
    -0
      modules/juce_core/text/juce_CharacterFunctions.h
  3. +3
    -18
      modules/juce_core/xml/juce_XmlElement.cpp

+ 6
- 1
modules/juce_core/javascript/juce_JSON.cpp View File

@@ -351,9 +351,14 @@ struct JSONFormatter
auto d = static_cast<double> (v);
if (juce_isfinite (d))
out << String (d, maximumDecimalPlaces);
{
String doubleString (d, maximumDecimalPlaces);
out << doubleString.substring (0, (int) CharacterFunctions::findLengthWithoutTrailingZeros (doubleString.getCharPointer()));
}
else
{
out << "null";
}
}
else if (v.isArray())
{


+ 29
- 0
modules/juce_core/text/juce_CharacterFunctions.h View File

@@ -378,6 +378,35 @@ public:
return readDoubleValue (text);
}
/** If the input is a string representation of a floating-point number, this will
find the length of the string without any trailing zeros.
*/
template <typename CharPointerType>
static size_t findLengthWithoutTrailingZeros (CharPointerType text)
{
auto start = text;
auto end = text + ((int) text.length());
for (auto e = end; e > start + 1; --e)
{
auto lastChar = *(e - 1);
if (lastChar != '0')
{
if (lastChar == '.')
return (size_t) (e + 1 - start);
for (auto s = start; s < e; ++s)
if (*s == '.')
return (size_t) (e - start);
break;
}
}
return (size_t) (end - start);
}
//==============================================================================
/** Parses a character string, to read an integer value. */
template <typename IntType, typename CharPointerType>


+ 3
- 18
modules/juce_core/xml/juce_XmlElement.cpp View File

@@ -578,26 +578,11 @@ void XmlElement::setAttribute (const Identifier& attributeName, const int number
setAttribute (attributeName, String (number));
}
static String trimTrailingZeros (const String& input)
{
auto pointPos = input.indexOfChar ('.');
if (pointPos == -1)
return input;
auto start = input.getCharPointer();
auto minPos = start + pointPos + 1;
auto ptr = start + input.length() - 1;
while (ptr != minPos && *ptr == '0')
--ptr;
return input.substring (0, (int) (ptr - start) + 1);
}
void XmlElement::setAttribute (const Identifier& attributeName, const double number)
{
setAttribute (attributeName, trimTrailingZeros ({ number, 20 }));
String doubleString (number, 20);
setAttribute (attributeName,
doubleString.substring (0, (int) CharacterFunctions::findLengthWithoutTrailingZeros (doubleString.getCharPointer())));
}
void XmlElement::removeAttribute (const Identifier& attributeName) noexcept


Loading…
Cancel
Save