【发布时间】:2020-09-11 17:16:29
【问题描述】:
这段代码:
cout<< to_string(x) + "m ----> " + to_string(x *0.001)+ "km"<<endl;
有了这个输出:
0.002000
但是,我想删除尾随的额外零,但它应该在一行代码中,因为我有很多行像上面那样。
【问题讨论】:
-
任何有用的 cmets ~ 非常感谢!
这段代码:
cout<< to_string(x) + "m ----> " + to_string(x *0.001)+ "km"<<endl;
有了这个输出:
0.002000
但是,我想删除尾随的额外零,但它应该在一行代码中,因为我有很多行像上面那样。
【问题讨论】:
试试这个片段:
cout << "test zeros" << endl;
double x = 200;
cout << "before" << endl;
cout<< std::to_string(x) + "m ----> " + std::to_string(x *0.001)+ "km"<<endl;
std::string str = std::to_string(x * 0.001);
str.erase ( str.find_last_not_of('0') + 1, std::string::npos );
cout << "after" << endl;
cout<< std::to_string(x) + "m ----> " + str + "km"<<endl;
输出:
test zeros
before
200.000000m ----> 0.200000km
after
200.000000m ----> 0.2km
这比std::setprecision 更好,因为您无需决定要保留多少个 num,而是让实现为您找到它。
这里是documentation 以获取更多信息。
【讨论】:
尝试使用std::setprecsion()
设置小数精度
设置用于在输出操作中格式化浮点值的小数精度。
所以在你的情况下,你可以使用:
std::cout << std::setprecision(3)
这将删除从 0.0020000 到 0.002 的尾随零
编辑
当您想在代码中使用 to_string 时,以下代码可以工作:
#include <iostream>
using namespace std;
int main(){
int x=1;
string str2 = to_string(x *0.001);
str2.erase ( str2.find_last_not_of('0') + 1, std::string::npos );;
std::cout<<to_string(x)+ "m ----> " + str2+ "km";
}
【讨论】:
to_string,而不是std::cout。
to_string。如重复问题中所述,您无法阻止 to_string 添加尾随零。如果您使用cout << x << "m ----> " << x * 0.001 << "km" << endl,尽管您可以使用setprecision 之类的东西来控制格式。