How to format a number with + and - sign in Delphi
delphi, numbers, string-formatting
Solution
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;
Problem
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.