【问题标题】:How to correctly convert "strings" to "double"? [duplicate]如何正确将“字符串”转换为“双精度”? [复制]
【发布时间】:2020-06-10 08:01:45
【问题描述】:

最后一个十进制值不会转换为double 并且不会出现在打印中。如何解决这个问题?

#include <iostream>

using namespace std;

double toDouble(const char* str)
{
   return stod(str);
}

int main()
{
    string text = "10158.34";
    double value = toDouble(text.c_str());
    cout << value << endl;

    return 0;
} 

谢谢。

【问题讨论】:

标签: c++


【解决方案1】:

默认输出设置是打印六位有效数字;见std::setprecision

例子:

#include <iostream>
#include <iomanip>
#include <string>

int main()
{
    std::string text = "10158.34";
    double value = std::stod(text);
    std::cout << std::setprecision(100) << value << std::endl;
} 

打印 10158.34000000000014551915228366851806640625,因为 10158.34 不能完全表示为 double

【讨论】:

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