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 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With