c++ - Remove trailing 0s and decimal if necessary from string -
i'm trying remove trailing zeros decimal, removing decimal if there no more trailing zeros.
this string produced boost's gmp_float string output of fixed.
this attempt, 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 remove trailing 0s if decimal present, removing decimal if there no more 0s after decimal point?
you need change to:
while( toformat.find(".")!=string::npos // !=string::npos important!!! && toformat.substr( toformat.length() - 1, 1) == "0" || toformat.substr( toformat.length() - 1, 1) == "." ) { toformat.pop_back(); } the key here add !=string::npos. when not found, std::basic_string::find() return std::basic_string::npos, not equal false (not expect).
static const size_type npos = -1;
Comments
Post a Comment