c++ - 在 C++ 中不使用科学记数法将字符串转换为 double

标签 c++ string double precision scientific-notation

我有一个字符串变量,想把它转换成没有任何科学记数法的 double 变量。我尝试使用 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::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

关于c++ - 在 C++ 中不使用科学记数法将字符串转换为 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62335017/

相关文章:

c++ - 自定义类指针作为无序映射键

c++ - 添加到多个 std 容器时 C++ 中的异常安全

java分割字符串函数

c++ - 从内存中提取 double 的字节值

c++ - C++ 中的 "=="有时会为相同的 double 给出不同的结果

c++ - 为什么这段代码中继承的函数隐藏在基类中?

c++ - 通过函数遍历c数组

java - java中按数字分割数组

Java和Weka : Creating a string attribute

c - IEEE754中是否有关于加法的中性元素