将浮点数格式化为###.##(两位小数)

vol*_*vox 8 delphi

拥有:

var
Difference: DWORD // difference shows in milliseconds
// List.Items.Count can be any 0 to ######## 
[...]
sb.panels[2].Text  := FloatToStr((((List.Items.Count) / difference) / 1000)); 
Run Code Online (Sandbox Code Playgroud)

我想将结果文本格式化为任意###.##(两位小数).使用FloatToStrF并不成功(似乎没有用DWORD).

Ral*_*ach 9

为什么不使用带格式字符串的格式函数?例:

sb.panels[2].Text := Format('%8.2f',[123.456]);
Run Code Online (Sandbox Code Playgroud)

其他功能将是

function FormatFloat(const Format: string; Value: Extended): string; overload;
function FormatFloat(const Format: string; Value: Extended; const FormatSettings: TFormatSettings): string; overload; 
Run Code Online (Sandbox Code Playgroud)


Arg*_*tyr 5

只是想知道这是数学而不是格式化的问题.为什么要将项目数除以1000?你的意思是将毫秒(你的差异变量)除以1000吗?也许这就是你想要的:

EventRate := (List.Items.Count) / (difference / 1000);  // events per second; to make it per minute, need to change 1000 to 60000
Run Code Online (Sandbox Code Playgroud)

当然,您仍然希望格式化结果.你需要它作为变量或类属性:

MyFormatSettings: TFormatSettings;
Run Code Online (Sandbox Code Playgroud)

那么,你需要做一次,例如FormShow:

getlocaleformatsettings(locale_system_default, MyFormatSettings);
Run Code Online (Sandbox Code Playgroud)

最后,这应该工作:

sb.panels[2].Text := format('%5.2f', EventRate, MyFormatSettings);
Run Code Online (Sandbox Code Playgroud)