【问题标题】:Conversion of string to double without scientific notation in C++在C ++中将字符串转换为没有科学记数法的double
【发布时间】:2020-06-11 23:09:16
【问题描述】:

我有一个字符串变量,想在没有任何科学记数法的情况下将其转换为双精度。我尝试使用std::stod,但这不起作用。

std::stringstream timestamp;
timestamp << t_val;
string test = timestamp.str();
cout << test << endl; // this gives 1506836639.96
double d = std::stod(test);
cout << d << endl; // This gives 1.50684e+09 instead of 1506836639.96

我尝试使用setprecisionfixed,但我无法将结果存储到变量中。有没有办法可以将test (1506836639.96) 的值存储为双精度值?

【问题讨论】:

  • 科学记数法在打印输出中,而不是在double 值中。
  • 使用这个值进行计算,但是当你最终想要打印它时,通过std::to_string将它转换回字符串。

标签: c++ string double precision scientific-notation


【解决方案1】:

科学记数法与std::cout有关,与值的存储方式无关,因此在打印值之前必须使用std::fixed

std::cout << std::fixed << std::setprecision(2) << d << std::endl;

正如您在演示中看到的那样,这很好用,它应该也适合您。

由于@goodvibration commented std::to_string 也有效,但在这种情况下无法以简单的方式重新定义默认数字或小数位。

std::cout << std::to_string(d) << std::endl;

Live demo

【讨论】:

    猜你喜欢
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 2017-12-24
    相关资源
    最近更新 更多