Recently, we had a project in C++. One problem I encountered was to properly format a double so that it displayed two decimal places. I'm used to programming in JAVA and what I'd do is to use the DecimalFormat class. In C/C++ there doesn't seem to be a solution, or at least an obvious one.
Without the DecimalFormat class, I would have either: separate the whole number and decimal values and just insert a decimal point inbetween. Or, search for the decimal point and either add trailing zeroes as needed or truncate it to two decimal places.
Doing that in C++ seems quite long. I could do that but it seems a bit crude. In the end, I did this:
#include
#include
using namespace std;
string moneyf(double d)
{
char temp[50];
sprintf(temp, "%0.2f", d);
return string(temp);
}
It works and it's shorter. In C, you'd include stdio.h instead of cstdio and return a char[].
Maybe this is the solution, maybe there's an even less crude way to do this. If you have any suggestions, they're very welcome :D