double to CString with dynamic number of decimal digits

string.Format(_T("%5f"), number);

I want to convert double-type value to CString, but the problem is that if value is 13, the CString will be "13.00000" (assume formatting is set to 5 decimal digits). I want CString to be "13" instead, or better yet "13.0" (if possible) to show user that the value is precise.
I could convert double-type value to char array and remove all necessary elements, and then convert the array to CString, but I'd like to write this more conveniently.
Is there any other way to do this? Maybe something like setpresicion for console output: http://www.cplusplus.com/reference/iostream/manipulators/setprecision/
You can use setprecision like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <iomanip>
#include <sstream>

int main ()
{
	double d = 13.001234;

	std::ostringstream oss; // output to string
	oss << std::setprecision(7) << d;

	std::string str = oss.str(); // retrieve output string

	std::cout << "str = " << str << std::endl;

  return 0;
}
Last edited on
try
string.Format(_T("%.1f"), number); // formatting will show 1 decimal digit .
This works with printf so it should work here too.
@Galik: But will this work with CString-type of string (I need this for MFC application)? I did this for now, works without issues:

1
2
3
4
5
6
7
8
9
10
	char resCh[40] = {'\0'};
	sprintf(resCh, "%f", result);
	i=39;
	while(resCh[i] == '0' || !resCh[i]) {
		if (resCh[i-1] == '0') {
			resCh[i] = '\0';
		}
		i--;
	}
	calcF.Format(_T("%S"), resCh);


@Null: I only gave number 13 as example. If the number is 13.4, then I want to format CString as "%.2f", if 13.45, then "%.3f" and so on... But I want to make all this as dynamic as possible.
I don't use windows but I don't see why you can't do this:

1
2
3
4
5
6
7
8
9
	double d = 13.001234;

	std::ostringstream oss; // output to string
	oss << std::setprecision(7) << d;

	CString str = oss.str().c_str(); // retrieve output string

	// ... etc...
Topic archived. No new replies allowed.