user965369
user965369

Reputation: 5743

CString.Format with variable float precision

I have a float value: (data->val) which could be of three possible float precisions: %.1f, %.2f and %.3f how would I format it using CString::Format to dsiplay only the number of decimal points necessary? eg:

CString sVal;

sVal.Format(L"%.<WHAT GOES HERE?>f", data->val);
if(stValue)
    stValue->SetWindowText(sVal);

As in I don't want any additional zeros on the end of my formatted string.

Upvotes: 6

Views: 16051

Answers (2)

Zaiborg
Zaiborg

Reputation: 2522

its some time ago, but maybe this will work...

CString getPrecisionString(int len)
{
   CString result;
   result.format( "%s%d%s","%.", len, "f" );
   return result;
}

// somewhere else
CString sVal;

sVal.Format(getPrecisionString(2), data->val);
if(stValue)
    stValue->SetWindowText(sVal);

the other way is, to cut the '0's just after adding the %.3f value with

sVal.trimEnd('0')

but is dangerous cuz you may have the '.' at the end...

Upvotes: 1

user7116
user7116

Reputation: 64148

If you know the precision you'd like simply use %.*f and supply the precision as an integer argument to CString::Format. If you'd like the simplest effective representation, try %g:

int precision = 2; // whatever you figure the precision to be
sVal.Format(L"%.*f", precision, data->val);
// likely better: sVal.Format(L"%g", data->val);

Upvotes: 8

Related Questions