String breaking change

Yeah, apologies for this one being a bit of a messy change. The problem was that it was never intended to work the way it did, but a test had somehow been added that checked for the wrong result, which made it all look legit. The function as it stood was full of edge-cases where its behaviour would be ambiguous or problematic - it really wasn’t very good, and IIRC the reason I changed it was because it caused bizarre problems in something else I was working on.

We discussed the fact that it would be a breaking change but figured that surely nobody would actually be relying on the not-quite-as-expected behaviour… so we decided to change it… and clearly it’s a mistake to make assumptions about how people might be using your code!

I don’t want to revert it though. We don’t want the old behaviour back, and we don’t want to get into a feature-creep situation by tagging on extra parameters to this method for more formatting options.

What we all really want is a proper, comprehensive system for formatting numeric strings with lots of nice, clear options, and that’s not something that belongs in the String class as a method, it needs to be done in a dedicated class devoted to number->string conversion that can cover lots of use-cases.

I’d really like to see that added (have wanted to do it for years), but it’d take a bit of planning and time to implement, so in the meantime, perhaps just add a free function to your own project like this:

static String doubleToStringWithMinDecimalPlaces (double value, int minDecimalPlacesAfterPoint)
{
    String s (value, minDecimalPlacesAfterPoint);
    auto dot = s.indexOfChar ('.');
    auto len = s.length();
    auto paddingNeeded = minDecimalPlacesAfterPoint;

    if (dot < 0)
        s << '.';
    else
        paddingNeeded -= (len - dot - 1);

    return paddingNeeded > 0 ? s + String::repeatedString ("0", paddingNeeded) : s;
}

Having your own free function also means you have more control over what happens in edge-cases, e.g. if the number is so large that scientific notation is needed, or what happens if it’s an NaN, or

1 Like