删除 C 中的尾随零

新手上路,请多包涵

我想问如何去除小数点后的尾随零?

我已经阅读了很多关于它的主题,但我并没有清楚地理解它们。你能告诉我任何容易理解的方法吗?

例如 12.50 到 12.5,但实际输出为 12.50

原文由 Trương Đức Vinh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 734
1 个回答

这是恕我直言在 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;
}

原文由 nielsen 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题