这个例程被称为无数次,以创建充满数字的大型csv文件.有没有更有效的方法来实现这一目标?
static std::string dbl2str(double d)
{
std::stringstream ss;
ss << std::fixed << std::setprecision(10) << d; //convert double to string w fixed notation, hi precision
std::string s = ss.str(); //output to std::string
s.erase(s.find_last_not_of('0') + 1, std::string::npos); //remove trailing 000s (123.1200 => 123.12, 123.000 => 123.)
return (s[s.size()-1] == '.') ? s.substr(0, s.size()-1) : s; //remove dangling decimal (123. => 123)
}
Run Code Online (Sandbox Code Playgroud) 我想问一下如何去掉小数点后面的零?
我读过很多有关它的主题,但我不太清楚它们。你能告诉我一些简单的理解方法吗?
例如12.50改为12.5,但实际输出是12.50
将浮点数格式化为不带尾随零的字符串的推荐方法是什么?
to_string()返回"1.350000"为sprintf。我不需要固定的小数位数...
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = to_string(1.35);
cout << s << endl;
}
Run Code Online (Sandbox Code Playgroud)