gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:25:16 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com