浮点数 – 在Inno Setup Pascal Script中将RoundTruncate浮点数转换为N个小数位

浮点数 – 在Inno Setup Pascal Script中将RoundTruncate浮点数转换为N个小数位,第1张

概述这看起来不像Inno Setup问题,但实际上与其有用的Pascal脚本有关. 我编写了一个代码来进行浮点计算. Height, DivisionOfHeightWidth, Width: Integer;Height := 1080;Width := 1920;DivisionOfHeightWidth := Width / Height;Log('The Division Of H 这看起来不像Inno Setup问题,但实际上与其有用的Pascal脚本有关.

我编写了一个代码来进行浮点计算.

Height,divisionOfheightWIDth,WIDth: Integer;Height := 1080;WIDth := 1920;divisionOfheightWIDth := WIDth / Height;Log('The division Of Height and WIDth: ' + IntToStr(divisionOfheightWIDth));

编译器日志给出输出:

The division Of Height and WIDth: 1

我希望这个编译器输出改为:

The division Of Height and WIDth: 1.77

我不能将Height和WIDth声明为Extended,Single或Double,因为它们在大多数情况下作为Integer返回,所以我需要将这两个Integers转换为两个Singles.

做完之后:

Height,WIDth: Integer;HeightF,WIDthF,divisionOfheightWIDthF: Single;Height := 1080;WIDth := 1920;HeightF := Height;WIDthF := WIDth;divisionOfheightWIDthF := WIDthF / HeightF;Log('The division Of Height and WIDth: ' + floatToStr(divisionOfheightWIDthF));

编译器日志现在给出输出:

The division Of Height and WIDth: 1.777777791023

但是如何才能将此输出设为1.77? (舍入不是1.78)
我的意思是我怎么能将这个1.777777791023舍入到两个小数位,如1.77?

如果像1.77那样四舍五入是不可能的,我怎么能像1.78一样围绕它呢?

提前致谢.

解决方法 如果舍入是可以接受的,一个简单的解决方案是使用 Format function:

var  Height,WIDth: Integer;  divisionOfheightWIDthF: Single;begin  ...  divisionOfheightWIDthF := Single(WIDth) / Height;  Log(Format('The division Of Height and WIDth: %.2f',[divisionOfheightWIDthF]));end;

有关格式字符串的详细信息,请参阅Format function的Delphi文档.

请注意,格式使用特定于区域设置的数字格式(特别是小数分隔符).

如果你真的需要截断,你需要自己实现它:

var  Height,WIDth: Integer;  divisionOfheightWIDthF: Single;  S: string;  P: Integer;begin  ...  divisionOfheightWIDthF := Single(WIDth) / Height;  S := floatToStr(divisionOfheightWIDthF);  P := Pos('.',S);  if P < Length(S) - 2 then  begin    SetLength(S,P + 2);  end;  Log(S);end;

以上工作在Unicode Inno Setup中仅作为Ansi版本,floatToStr使用特定于语言环境的小数分隔符,即并不总是..

总结

以上是内存溢出为你收集整理的浮点数 – 在Inno Setup Pascal Script中将Round / Truncate浮点数转换为N个小数位全部内容,希望文章能够帮你解决浮点数 – 在Inno Setup Pascal Script中将Round / Truncate浮点数转换为N个小数位所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1261311.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存