Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 906
user965369 Avatar asked Feb 19 '23 14:02

user965369


2 Answers

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);
like image 87
user7116 Avatar answered Feb 21 '23 03:02

user7116


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...

like image 25
Zaiborg Avatar answered Feb 21 '23 03:02

Zaiborg