Question

I am working on a money program. Currently I am trying to make a part in the program that displays a list that shows every transaction that was made in the session. My problem is that when I convert the money amount to a string instead of displaying something like 100.35 in when converted to a string it instead displays something like 100.35000000. I was wondering if there was any way I could make the program drop the additional zeros? Here is a sample of how I convert the numbers to a string

int main(){

     double samplemoney=100.35;
     string sample="Today we made $";
     string comsample;
     comsample=sample+std::tostring(money)+".";
     cout<<comsample<<endl;
     return 0;

}

In my main program this part is handled with a class but as I said earlier it seems like no matter what the money value I put in is it will display a series of zero and I want my program to drop the unnecessary zeros.

Was it helpful?

Solution

Let's say you have this number:

    double number = 190.0391000;

If the problem is displaying the value you may use

std::cout << std::setprecision(5) << number

where f is the number you want to show.

If your problem is having a string with a finite precision you can use sprintf() in the following way:

char arr[128];
sprintf(arr,"%3.2f", number);
std::string formattedstring(arr);

or in a more C++ oriented way something like this

std::stringstream strn;
strn.precision(2);
strn << std::fixed << number;

and then you get the string in the following way:

std::string formattedstring = strn.str();

I attach the full text of program here... tested on my machine:

#include <sstream>
#include <iostream>
int main() {
    float number=100.24324232;
   std::stringstream strn;
   strn.precision(2);
   strn << std::fixed << number;
   std::cout << strn.str() << "\n";
   return( 0 );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top