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.

1
  • Any helpful comments ~ Much appreciated ! Commented May 25, 2020 at 5:05

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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";
}

6 Comments

This isn't related to the problem. The zeros are coming from to_string, not std::cout.
cout<<to_string(x) + "m ----> " + to_string(x *0.001)+ "km"<<endl; How to implement that in this code? i tried 2 ways, didnt worked.
@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.
@BessieTheCow yepppp thank you, works prefectly!
Well, to edit my answer, they below code works : #include <iostream> 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<<str1 + "m ----> " + str2+ "km"; }
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.