如何在Delphi上正确格式化浮点数字符串?

时间:2021-05-06 21:38:44

I need to call Format function to return the following strings:

我需要调用Format函数来返回以下字符串:

1.0 -> "1 or 1.0"
1.01 - > "1.01"
1.001 - > "1.001"
1.0000001 -> "1.0000001"

It it possible? The standard format string %0:f returns only two digits after the point (for example, "1.01").

有可能吗?标准格式字符串%0:f仅返回该点后的两位数(例如,“1.01”)。

1 个解决方案

#1


6  

Use the %g general format string:

使用%g通用格式字符串:

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

begin
  Writeln(Format('%g', [1.0]));
  Writeln(Format('%g', [1.01]));
  Writeln(Format('%g', [1.001]));
  Writeln(Format('%g', [1.0000001]));
end.

Output

1
1.01
1.001
1.0000001

#1


6  

Use the %g general format string:

使用%g通用格式字符串:

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

begin
  Writeln(Format('%g', [1.0]));
  Writeln(Format('%g', [1.01]));
  Writeln(Format('%g', [1.001]));
  Writeln(Format('%g', [1.0000001]));
end.

Output

1
1.01
1.001
1.0000001