How to format a number using the + and - icons in Delphi

Using Delphi, is there a way to force character output when using the Format function for integers? For positive numbers, the prefix "+" (plus) is used, for negative numbers, the prefix "-" (minus). Zero processing is not important in my case (it can have either a sign prefix or none).

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

+4
source share
1 answer

As David has already commented , the Format function does not offer a format specifier for this purpose.

If you really need a one 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 to make a separate (library) procedure:

 function FormatInt(Value: Integer): String; begin if Value > 0 then Result := '+' + IntToStr(Value) else Result := IntToStr(Value); end; 
+11
source

All Articles