Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a float to ###.## (two decimals)

Tags:

delphi

Having :

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

I want to format the resulting text to any ###.## (two decimals). Using FloatToStrF is no success (does'nt seem to work with DWORD).

like image 232
volvox Avatar asked Jul 03 '09 21:07

volvox


2 Answers

Why don't you use format function with format strings? Example:

sb.panels[2].Text := Format('%8.2f',[123.456]);

Other functions would be

function FormatFloat(const Format: string; Value: Extended): string; overload;
function FormatFloat(const Format: string; Value: Extended; const FormatSettings: TFormatSettings): string; overload; 
like image 157
Ralph M. Rickenbach Avatar answered Sep 22 '22 04:09

Ralph M. Rickenbach


Just wondering if this is a problem with math rather than formatting. Why are you dividing the number of items by 1000? Do you mean to divide milliseconds (your Difference variable) by 1000? Maybe this is what you want:

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

Of course, you'll still want to format the result. You'll need this as a variable or class property:

MyFormatSettings: TFormatSettings;

then, you'll need to do this once, e.g. in FormShow:

getlocaleformatsettings(locale_system_default, MyFormatSettings);

finally, this should work:

sb.panels[2].Text := format('%5.2f', EventRate, MyFormatSettings);
like image 29
Argalatyr Avatar answered Sep 21 '22 04:09

Argalatyr