字符串到双精度转换C ++

编程入门 行业动态 更新时间:2024-10-07 22:18:40
本文介绍了字符串到双精度转换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 ++

本文发布于:2023-11-30 13:30:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650157.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   精度

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!