2009. december 20., vasárnap

Format Float with Comma


Problem/Question/Abstract:

Format Float with Comma

Answer:

function FormatNum(Value: Extended; Decimal: Integer): string;
var
  SLen, SPos: Integer;
  SVal: string;
begin
  Str(Value: 0: Decimal, SVal);
  SLen := Length(SVal);
  if Decimal = 0 then
    SPos := SLen - 2
  else
    SPos := SLen - (Decimal + 3);
  while SPos > 1 do
  begin
    Insert(',', SVal, SPos);
    SPos := SPos - 3;
  end;
  Result := SVal;
end;

Also, you can simply do this:

i: Extended;
s: string;

i := 1000.123456;
s := Format('%.2n', [i]);

The value of s will be 1,000.12

You can also add your own characters, so you could do something like this:

s := Format('$%.2n', [i]);

This would output $1,000.12

So, good luck in your number to string formatting.

Nincsenek megjegyzések:

Megjegyzés küldése