具有变量float精度的CString.Format

use*_*369 3 c++ string floating-point mfc

我有一个浮动值:( data->val),这可能是三种可能的浮动精度:%.1f,%.2f%.3f我将如何使用它格式化CString::Format到dsiplay只需要小数点的数字?例如:

CString sVal;

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

因为在我的格式化字符串的末尾我不希望任何额外的零.

use*_*116 7

如果你知道你想要的精度,只需使用%.*f并提供精度作为整数参数CString::Format.如果您想要最简单的有效表示,请尝试%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);
Run Code Online (Sandbox Code Playgroud)