cstring.format具有可变浮点精度

CString.Format with variable float precision

本文关键字:精度 format cstring      更新时间:2023-10-16

我有一个float值:( data->val),它可能是三个可能的浮点精度: %.1f%.2f and %.3f我如何使用 CString::Format将其格式化为只需dsiplay所需的小数次数?例如:

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

我不希望在我的格式字符串的末端任何其他零。

如果您知道只需使用%.*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);

它前一次,但这也许会起作用...

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);

另一种方法是在添加%.3F值

之后剪切0是
sVal.trimEnd('0')

,但很危险,因为您可能拥有'。最后...