C++中的字符串转双精度浮点数转换

6

我想把一个字符串转换成双精度浮点数,但是我的双精度浮点数在第三位小数处被截断了。

我的字符串看起来像这样:"-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 截断小数位数。 - Jongware
3个回答

6
如果我是你,我会写下以下这段代码:
#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 而不是低级操作从字符串中获取双精度数。

您可以在ideone运行网站上看到此示例


我遇到了一个未声明的标识符'stod'。我已经包含了string和iostream。setLatitude(string lat){ //this->lat = (double)atof(lat.c_str()); this->lat = stod(lat); } - jshah
1
@jshah:你需要使用C++11支持进行编译,例如在gcc和clang中使用-std=c++11。 - László Papp
我的版本是:$$ g++ -v Apple LLVM 版本 5.1 (clang-503.0.38)(基于 LLVM 3.4svn) - jshah
如何最好地更新g++?是的,Mac。 - jshah
仍然得到相同的错误。 - jshah
显示剩余5条评论

3

另外,您可能还想查看boost :: lexical_cast进行字符串到double转换。 http://www.boost.org/doc/libs/1_55_0/doc/html/boost_lexical_cast.html - teambob
这样是行不通的。原帖需要至少精度为11。 - László Papp
谢谢!这适用于精度16。 - jshah
@jshah:不是,是14,符号和小数点不算在内,但你原来的代码真的很hack'ish,没有使用现有的功能(strtod/stod)。另外,双重转换是多余的,因为如果你查看man页面,那就是atof的返回值定义。 - László Papp
如果你正在使用C++11,stod()可能是一个不错的选择,而不是lexical_cast()。 - teambob

2

正确的C++11解决方案是使用 stod - 将字符串转换为双精度浮点数。如果您的字符串不是有效数字,该函数会抛出异常,因此您可能应该在该函数周围使用 try ... catch

然而,您目前使用的代码使用 atof 完美地 [假设您特定标准C库中没有错误] 转换为 double (尽管名称为 Ascii TO Float,它返回一个 double 值),只是没有打印足够的数字,请使用 precisionsetprecision 来告诉 cout 使用多少位数字,例如:

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

您需要包含<iomanip>才能使setprecision起作用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接