【问题标题】:Converting string to double keeps rounding to the whole number将字符串转换为双精度数会保持舍入为整数
【发布时间】:2020-06-25 22:09:02
【问题描述】:

我正在尝试将 string 十进制数转换为 double,但是当我使用 atof() 函数时,我的数字最终会四舍五入为整数。

#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
string num = "135427.7000";
double r = atof(num.c_str());
cout << r << endl;
}

输出是:

135428

我想要:

135427.7

【问题讨论】:

    标签: c++ string type-conversion double rounding


    【解决方案1】:

    cout 这样做,而不是 atof()

    更准确地说,operator&lt;&lt;,它将格式化的数据插入到std::ostream

    您可以使用&lt;iomanip&gt; 标准库中的std::setprecision() 打印小数点:

    cout << setprecision(7) << r << endl;
    

    cout << fixed << setprecision(1) << r << endl;
    

    如果要打印整个135427.7000

    cout << fixed << setprecision(4) << r << endl;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      相关资源
      最近更新 更多