删除 C++ 中的尾随零

Trư*_*inh 10 c++

我想问一下如何去掉小数点后面的零?

我读过很多有关它的主题,但我不太清楚它们。你能告诉我一些简单的理解方法吗?

例如12.50改为12.5,但实际输出是12.50

nie*_*sen 15

恕我直言,这是 C++ 中过于复杂的一件事。无论如何,您需要通过设置输出流的属性来指定所需的格式。为了方便起见,定义了许多操纵器。

在这种情况下,您需要设置fixed表示形式并设置precision为 2,以便使用相应的操纵器在点后四舍五入到 2 位小数,请参见下文(请注意,这setprecision会导致四舍五入到所需的精度)。棘手的部分是删除尾随零。据我所知,C++ 不支持开箱即用,因此您必须进行一些字符串操作。

为了能够做到这一点,我们首先将值“打印”到一个字符串,然后在打印之前操作该字符串:

#include <iostream>
#include <iomanip>

int main()
{ 
    double value = 12.498;
    // Print value to a string
    std::stringstream ss;
    ss << std::fixed << std::setprecision(2) << value;
    std::string str = ss.str();
    // Ensure that there is a decimal point somewhere (there should be)
    if(str.find('.') != std::string::npos)
    {
        // Remove trailing zeroes
        str = str.substr(0, str.find_last_not_of('0')+1);
        // If the decimal point is now the last character, remove that as well
        if(str.find('.') == str.size()-1)
        {
            str = str.substr(0, str.size()-1);
        }
    }
    std::cout << str << std::endl;
}
Run Code Online (Sandbox Code Playgroud)