Search code examples
c++stringzerodecimal-pointtrailing

Remove trailing 0s and decimal if necessary from string


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?


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;