4

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.

4

1 回答 1

11

就像David 已经评论过的那样,该Format函数没有为此目的提供格式说明符。

如果你真的想要一个单行解决方案,那么我想你可以使用类似的东西:

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

但我更愿意制作一个单独的(库)例程:

function FormatInt(Value: Integer): String;
begin
  if Value > 0 then
    Result := '+' + IntToStr(Value)
  else
    Result := IntToStr(Value);
end;
于 2012-07-02T11:21:17.597 回答