0

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.

dboy
  • 1,004
  • 2
  • 16
  • 24

2 Answers2

1

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";
}
Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32
  • This isn't related to the problem. The zeros are coming from `to_string`, not `std::cout`. – eesiraed May 25 '20 at 05:17
  • cout< " + to_string(x *0.001)+ "km"< – 3.00AMCoder May 25 '20 at 05:18
  • @3.00AMCoder It seems like you don't need to use `to_string` at all in your code. As explained in the duplicate question, you can't prevent `to_string` from adding trailing zeros. If you do `cout << x << "m ----> " << x * 0.001 << "km" << endl` though you can control the formatting with things like `setprecision`. – eesiraed May 25 '20 at 05:21
  • @BessieTheCow yepppp thank you, works prefectly! – 3.00AMCoder May 25 '20 at 05:24
  • Well, to edit my answer, they below code works : #include using namespace std; int main(){ int x=1; std::string str1 = std::to_string (x); string str2 = to_string(x *0.001); str1.erase ( str1.find_last_not_of('0') + 1, std::string::npos ); str2.erase ( str2.find_last_not_of('0') + 1, std::string::npos ); std::cout< " + str2+ "km"; } – Abhishek Bhagate May 25 '20 at 05:27
  • @3.00AMCoder: please consider, the solution is only works if you want to keep *three* digit after period. In case your other number doesn't looks like that, it won't work anymore. – dboy May 25 '20 at 05:39
1

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.

dboy
  • 1,004
  • 2
  • 16
  • 24