当前位置 : 主页 > 编程语言 > delphi >

Delphi FloatToStr – 为什么显示器不同?

来源:互联网 收集:自由互联 发布时间:2021-06-23
使用DEFAULT FloatToStr函数 FloatToStr('0.0000442615029219009') 输出 4.42615029219009E-5 小数点后丢一个零 FloatToStr('0.000442615029219009') 产生 0.000442615029219009 有人可以解释为什么第二种情况下的值不输出
使用DEFAULT FloatToStr函数

FloatToStr('0.0000442615029219009')

输出

4.42615029219009E-5

小数点后丢一个零

FloatToStr('0.000442615029219009')

产生

0.000442615029219009

有人可以解释为什么第二种情况下的值不输出

4.42615029219009E-4
documentation for FloatToStr包含答案:

The conversion uses general number format with 15 significant digits.

要解释该语句,您还需要参考topic describing the Format函数,特别是有关一般数字格式的文本(强调我的):

The value is converted to the shortest possible decimal string using fixed or scientific format. The number of significant digits in the resulting string is given by the precision specifier in the format string; a default precision of 15 is assumed if no precision specifier is present. Trailing zeros are removed from the resulting string, and a decimal point appears only if necessary. The resulting string uses the fixed-point format if the number of digits to the left of the decimal point in the value is less than or equal to the specified precision, and if the value is greater than or equal to 0.00001. Otherwise the resulting string uses scientific format.

不幸的是,文档实际上存在错误.而不是0.00001,它应该是0.0001.这个程序说明了这一点:

program FloatToStrScientificFixed;
{$APPTYPE CONSOLE}
uses
  System.SysUtils;

var
  d: Double;

begin
  d := 0.0001;
  Writeln(FloatToStr(d*0.9999999));
  Writeln(FloatToStr(d));
  Writeln(FloatToStr(d*1.0000001));
  Readln;
end.

对于您的示例,0.0000442615029219009小于0.0001,因此使用科学记数法进行格式化.但是0.000442615029219009大于0.0001,因此使用固定表示法进行格式化.

如果您希望输出始终使用科学记数法,请使用e format string格式化.

QC#107388

网友评论