如果需要,从字符串中删除尾随0和小数

时间:2014-04-15 15:50:50

标签: c++ string zero decimal-point trailing

我试图从小数中删除尾随零,如果没有更多的尾随零,则删除小数。

此字符串由boost gmp_float字符串输出固定。

生成

这是我的尝试,但我得到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;
}

如果存在小数,如何删除尾随0,如果小数点后不再有0 s,则删除小数?

2 个答案:

答案 0 :(得分:2)

您需要将其更改为:

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();
}

此处的关键是添加 !=string::npos 。如果找不到,std::basic_string::find()将返回std::basic_string::npos,这不等于false(不是您所期望的)。

static const size_type npos = -1;

答案 1 :(得分:0)

    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);
    }

在C ++中,您有std::string::find_last_not_of