在 C++ 中不使用科学记数法将字符串转换为双精度
Conversion of string to double without scientific notation in C++
我有一个字符串变量,想把它转换成没有任何科学记数法的双精度变量。我尝试使用 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
我尝试使用 setprecision
和 fixed
但我无法将结果存储到变量中。有没有办法可以将 test
(1506836639.96) 的值存储为双精度值?
科学计数法与std::cout
有关,而不是值的存储方式,因此在打印值之前必须使用std::fixed
:
std::cout << std::fixed << std::setprecision(2) << d << std::endl;
正如您在演示中看到的那样,它工作正常,它应该也适合您。
因为 std::to_string
也可以,但无法以简单的方式重新定义这种情况下的默认数字或小数位。
std::cout << std::to_string(d) << std::endl;
我有一个字符串变量,想把它转换成没有任何科学记数法的双精度变量。我尝试使用 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
我尝试使用 setprecision
和 fixed
但我无法将结果存储到变量中。有没有办法可以将 test
(1506836639.96) 的值存储为双精度值?
科学计数法与std::cout
有关,而不是值的存储方式,因此在打印值之前必须使用std::fixed
:
std::cout << std::fixed << std::setprecision(2) << d << std::endl;
正如您在演示中看到的那样,它工作正常,它应该也适合您。
因为 std::to_string
也可以,但无法以简单的方式重新定义这种情况下的默认数字或小数位。
std::cout << std::to_string(d) << std::endl;