Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a number with + and - sign in Delphi

Using Delphi, is there a way to enforce sign output when using the Format function on integers? For positive numbers a '+' (plus) prefix shall be used, for negative numbers a '-' (minus) prefix. The handling of Zero is not important in my case (can have either sign prefix or none).

I would like to avoid using format helper functions for each format and if-then-else solutions.

like image 509
blerontin Avatar asked Dec 21 '22 19:12

blerontin


1 Answers

Like David already commented, the Format function offers no format specifier to that purpose.

If you really want a single-line solution, then I suppose you could use something like:

uses
  Math;
const
  Signs: array[TValueSign] of String = ('', '', '+');
var
  I: Integer;
begin
  I := 100;
  Label1.Caption := Format('%s%d', [Signs[Sign(I)], I]);  // Output: +100
  I := -100;
  Label2.Caption := Format('%s%d', [Signs[Sign(I)], I]);  // Output: -100

But I would prefer making a separate (library) routine:

function FormatInt(Value: Integer): String;
begin
  if Value > 0 then
    Result := '+' + IntToStr(Value)
  else
    Result := IntToStr(Value);
end;
like image 144
NGLN Avatar answered Jan 04 '23 18:01

NGLN