How can I format string for float number on Delphi correctly?

不想你离开。 提交于 2019-12-13 08:42:39

问题


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

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").


回答1:


Use the %g general format string:

{$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


来源:https://stackoverflow.com/questions/24562127/how-can-i-format-string-for-float-number-on-delphi-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!