我想知道如何从整数转换为浮点值,而不分配给中间变量.有问题的代码如下所示:
Format('Theoretical peak scaling %6.2f', [ThreadCount])
Run Code Online (Sandbox Code Playgroud)
这显然在运行时失败,因为它ThreadCount
是一个整数.
我试过了明显的事
Format('Theoretical peak scaling %6.2f', [Double(ThreadCount)])
Run Code Online (Sandbox Code Playgroud)
并且编译器拒绝使用
E2089 Invalid typecast
Run Code Online (Sandbox Code Playgroud)
我知道我可以写
Format('Theoretical peak scaling %6.2f', [ThreadCount*1.0])
Run Code Online (Sandbox Code Playgroud)
但是读得很差,并且会诱使未来的维护者去除错误中的乘法.
有没有人知道在没有中间变量的情况下做到这一点的干净方法,以及让未来读者明白代码的方式?
这可能感觉很傻......但如果它是一个整数,为什么不只是:
Format('Theoretical peak scaling %3d.00', [ThreadCount]);
Run Code Online (Sandbox Code Playgroud)
这不像你在小数点后会有零而是零,对吗?
您可以选择使用record helper
内部类型:
type
TIntHelper = record helper for Integer
function AsFloat : Double;
end;
function TIntHelper.AsFloat: Double;
begin
Result := Self;
end;
Format('Theoretical peak scaling %6.2f', [ThreadCount.AsFloat])
Run Code Online (Sandbox Code Playgroud)
这是在XE3中添加的,但有一些来自Embarcadero的限制.由于只有一个助手可以在范围内,Emarcadero建议此功能仅供RTL内部使用.
来自Marco Cantu的报价:
我们建议您不要自己编写(尽管您可能希望将此作为我们不支持的类型的临时措施)
原因不仅仅是每个类规则的一个帮助器,而且这个行为在将来会发生变化,具有不同的编译器机制.所以,如果你有这个,不要为将来屏住呼吸.
参考:On Record/Class/Type Helpers
.
更新:在XE4
为整数内置辅助类,TIntegerHelper
,有一个方法ToDouble
.
使用RTTI
它可以使用内置语言元素解决这个问题:
Format('Theoretical peak scaling %6.2f',
[TValue.From<Integer>(ThreadCount).AsExtended])
Run Code Online (Sandbox Code Playgroud)
Just FTR,一个基准测试表明,Double(Variant(i))
内联助手i.AsFloat
具有可比性,而TValue.From<Integer>(i).AsExtended
速度则慢200倍.
这是学术性的,我会使用函数或 * 1.0 但这是有效的
Format('Theoretical peak scaling %6.2f', [Double(Variant(ThreadCount))])
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2143 次 |
最近记录: |