This code:
cout<< to_string(x) + "m ----> " + to_string(x *0.001)+ "km"<<endl;
with this outputting:
0.002000
However, I want to remove the trailing extra zeros, but it should be in a line of code as i have many lines like the above one.
This code:
cout<< to_string(x) + "m ----> " + to_string(x *0.001)+ "km"<<endl;
with this outputting:
0.002000
However, I want to remove the trailing extra zeros, but it should be in a line of code as i have many lines like the above one.
Try using std::setprecsion()
Set decimal precision
Sets the decimal precision to be used to format floating-point values on output operations.
So in your case, you can use :
std::cout << std::setprecision(3)
This will remove the trailing zeroes from 0.0020000 to 0.002
Edit
The below code works when you want to use to_string in your code :
#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";
}
try this snipet:
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;
with output:
test zeros
before
200.000000m ----> 0.200000km
after
200.000000m ----> 0.2km
it is better then std::setprecision
cause you don't need to decide how many num after period you want to keep, but let the implementation find it for you.
Here the documentation for some extra information.