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 0
s if a decimal is present, removing the decimal if there are no more 0
s after the decimal point?
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;