c++ - 字符串到 double 转换 C++

标签 c++ string double

<分区>

我正在尝试将字符串转换为 double ,但我的 double 在小数点后第三位被截断。

我的字符串如下所示:“-122.39381636393” 转换后它看起来像这样:-122.394

void setLongitude(string longitude){
    this->longitude = (double)atof(longitude.c_str());

    cout << "got longitude: " << longitude << endl;
    cout << "setting longitude: " << this->longitude << endl;
}

输出示例:

got longitude: -122.39381636393
setting longitude: -122.394

我想让它保留所有小数点,有什么提示吗?

最佳答案

如果我是你,我会写这段代码:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str = "-122.39381636393";
    std::cout.precision(20);
    cout << "setting longitude: " << stod(str) << endl;
    return 0;
}

基本上,您会更改如下内容:

  • 打印精度

  • stod 而不是低级操作来从字符串中取回 double。

可以看到on ideone running .

关于c++ - 字符串到 double 转换 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23449986/

相关文章:

string - 如何使用函数的参数作为变量的名称?

c++ - 类模板上的运算符重载

c++ - 将 unsigned char(BYTE) 数组转换为 const t_wchar* (LPCWSTR)

c++ - 如何在 C++ 的 protobuf 中使用反射将预分配消息设置为字段?

c++ - Linux 中的 gettimeofday 函数线程安全吗?

c - 在c中标记字符串的快速方法

c++ - 将不包含定界符的字符串末尾添加到 vector

java - 从文件中的一行解析 double 时忽略字母

java - 在双链表中插入新元素

java - 如何让两个整数的商向上舍入? (5/2)