本文介绍了字符串到双精度转换C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将字符串转换为双精度型,但是双精度型会在小数点后第三位被截断。
I'm trying to convert a string into a double but my double gets cut off at the 3rd decimal point.
我的字符串如下所示:-122.39381636393 转换后看起来像这样:-122.394
My string looks like this: "-122.39381636393" After it gets converted it looks like this: -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我希望它保留所有小数点,还有什么提示吗?
I want it to maintain all the decimal points, any tips?
推荐答案如果我是您:
#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; }基本上,您会更改以下内容:
Basically, you would change things like:
-
打印精度
precision for the printing
存储而不是低级操作来获得双精度
stod rather than low-level operation to get the double back from the string.
您可以看到它在运行ideone上。
更多推荐
字符串到双精度转换C ++
发布评论