【问题标题】:String to Double conversion C++ [duplicate]字符串到双精度转换C++ [重复]
【发布时间】:2014-06-20 10:15:36
【问题描述】:

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

我的字符串如下所示:“-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

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

【问题讨论】:

  • cout 截断小数位数

标签: c++ string double


【解决方案1】:

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

#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 而不是低级操作从字符串中获取双精度。

你可以看到on ideone running

【讨论】:

  • 我得到了一个未声明的标识符“stod”,我已经包含了字符串和 iostream。 setLatitude(string lat){ //this-&gt;lat = (double)atof(lat.c_str()); this-&gt;lat = stod(lat); }
  • @jshah:您需要使用 C++11 支持进行编译,例如-std=c++11 在 gcc 和 clang 的情况下。
  • 我正在使用 g++ -std=c++11 meetLocation.cpp 并得到同样的错误。
  • 我的版本是:$$ g++ -v Apple LLVM version 5.1 (clang-503.0.38)(基于LLVM 3.4svn)
  • 更新 g++ 的最佳方法是什么?是的,mac
【解决方案2】:

可能是 printing 截断精度,而不是从字符串到双精度的转换。

看看 ios_base::precision http://www.cplusplus.com/reference/ios/ios_base/precision/

例如 cout.precision(10); cout << "setting longitude: " << this->longitude << endl;

【讨论】:

  • 另外,您可能还想查看 boost::lexical_cast 的字符串到双重转换。 boost.org/doc/libs/1_55_0/doc/html/boost_lexical_cast.html
  • 这行不通。 OP 至少需要 11 的精度。
  • 谢谢!这适用于精度 16。
  • @jshah:不,14,符号和点不算数,但是您的原始代码确实是hack'ish,不使用现有功能(strtod/stod)。此外,双重转换是多余的,因为根据定义,如果您查看 the man page up,这就是 atof 的返回值。
  • 如果你使用 C++11 stod() 可能是个好主意,而不是 lexical_cast()
【解决方案3】:

正确的 C++11 解决方案是使用 stod - String TO Double。您可能应该在该函数周围使用try ... catch,因为如果您的字符串不是有效数字,它会引发异常。

但是,使用atof 的代码完美地[假设您的特定标准C 库中没有错误] 转换为double(尽管名称为Ascii TO Float,但它返回double 值),您只是没有打印足够的数字,使用precisionsetprecision 通知cout 要使用多少位,例如

cout << "Setting longitude: " << setprecision(15) << this->longitude << endl;

您需要包含&lt;iomanip&gt; 才能使setprecision 工作。

【讨论】:

    猜你喜欢
    • 2017-10-06
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 2013-10-10
    • 2015-04-10
    • 1970-01-01
    相关资源
    最近更新 更多