Question

I'm trying to remove trailing zeros from a decimal, removing the decimal if there are no more trailing zeros.

This string produced from a boost's gmp_float string output of fixed.

This is my attempt, but I'm getting std::out_of_range:

string trim_decimal( string toFormat ){
    while( toFormat.find(".") && toFormat.substr( toFormat.length() - 1, 1) == "0" || toFormat.substr( toFormat.length() - 1, 1) == "." ){
        toFormat.pop_back();
    }
    return toFormat;
}

How can I remove trailing 0s if a decimal is present, removing the decimal if there are no more 0s after the decimal point?

Was it helpful?

Solution

You need to change it to:

while( toFormat.find(".")!=string::npos   // !=string::npos is important!!!
    && toFormat.substr( toFormat.length() - 1, 1) == "0" 
    || toFormat.substr( toFormat.length() - 1, 1) == "." )
{
    toFormat.pop_back();
}

The key here is to add !=string::npos. When not found, std::basic_string::find() will return std::basic_string::npos, which is not equal to false (not what you expect).

static const size_type npos = -1;

OTHER TIPS

    auto lastNotZeroPosition = stringValue.find_last_not_of('0');
    if (lastNotZeroPosition != std::string::npos && lastNotZeroPosition + 1 < stringValue.size())
    {
        //We leave 123 from 123.0000 or 123.3 from 123.300
        if (stringValue.at(lastNotZeroPosition) == '.')
        {
            --lastNotZeroPosition;
        }
        stringValue.erase(lastNotZeroPosition + 1, std::string::npos);
    }

In C++ you have std::string::find_last_not_of

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top