删除尾随零-C ++

时间:2020-05-25 05:04:48

标签: c++ trailing

此代码:

cout<< to_string(x) + "m ----> " + to_string(x *0.001)+ "km"<<endl;

,其输出为: 0.002000

但是,我想删除尾随的多余零,但是它应该在一行代码中,因为我有很多类似上面的行。

2 个答案:

答案 0 :(得分:1)

尝试使用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";
}

答案 1 :(得分:1)

尝试此摘要:

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,因为您无需决定要保留多少个句号,而让实现为您找到。

documentation中获取一些其他信息。