浮点到字符串,不带尾随零
Float to string without trailing zeros
本文关键字:字符串 更新时间:2023-10-16
将浮点数格式化为不带尾随零的字符串的推荐方法是什么? to_string()
返回"1.350000"
,sprintf
也是如此。我不想要固定数量的小数...
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = to_string(1.35);
cout << s << endl;
}
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
stringstream ss;
ss << 1.35;
cout << ss.str();
return 0;
}
std::to_string
& sprintf
没有赋予您任何功能来控制将浮点数转换为字符串时获得的尾随零数。尝试使用 std::stringstream
代替,您将拥有控制尾随零所需的所有选项。