c++ - 如何在转换为字符串时打印 float 的小数部分

标签 c++

我有一个将浮点值转换为字符串的代码,我写的如下

#include <iostream>
#include <string>
#include <sstream> 
using namespace std;

int main() {
    float myFloat= 10.80;
    std::ostringstream ss;
    ss << myFloat;
    cout<<"value = " << ss.str();
    std::string s(ss.str());
    cout<<"value = " << s;

    return 0;
}

但问题是,当我的值为 10.66 时,它会变成 10.66,但当它的值为 10.80 时,它会变成 10.8,或者当它的值为 10.00 时,它只会变成 10。

如何打印完整的值

最佳答案

试试这段代码。 将 setprecision 函数与 '2' 一起使用。

#include <iostream>
#include <string>
#include <sstream> 
#include <iomanip>
using namespace std;

int main() {

float myFloat= 10.80;
stringstream stream;
stream << fixed << setprecision(2) << myFloat;
string s = stream.str();
cout<<"value = " << s;
       return 0;
}

enter image description here

关于c++ - 如何在转换为字符串时打印 float 的小数部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48839888/

相关文章:

c++ - C++ While 语句中的 AND 运算符

c++ - LNK2022:元数据操作失败:重复类型中的字段声明不一致

c++ - 为什么可以编译隐式转换

c++ - 如何使用 boost::gil 处理数字像素操作中的溢出?

c++ - 头文件应该插入两次吗?

c++ - 在 C++ 中将文件输入类型转换为 vector 类型

php - c++ 和 php 中的 openssl 加密

c++ - 通过创建 'state snapshot' 构建撤消和重做

绑定(bind)对象函数时出现 C++ 异步错误

c++ - 指针数组的问题