我有一个简单的循环:
<cfoutput>
<cfloop from="0.01" to="0.06" index="i" step="0.01">
<p>i=#i#</p>
</cfloop>
</cfoutput>
输出是:
i=0.01
i=0.02
i=0.03
i=0.04
i=0.05
预期值0.06
没有出现!如果我将“To”的值增加或减少0.01
,则循环可以正常工作。
I have created an example of the issue here on TryCF 。单击“运行代码”按钮生成输出。
有什么想法吗?
最佳答案
我的猜测是,这里的问题是 ColdFusion 如何处理数字。它将字符串“0.01”和“0.06”转换为数字,并且可能在某些时候失去精度。请记住,ColdFusion 是松散类型的。
ColdFusion does not use explicit types for variables, while Java is strongly typed. However, ColdFusion data does use underlying Java types to represent data.
From Java and ColdFusion data type conversions
我修改了 TryCF 上的 ColdFusion 示例,试图表明我的观点。我使用 javacast() 显式地将数字定义为 float 。 Try the new code here.
<cfloop from="#javacast('float','0.01')#"
to="#javacast('float','0.06')#"
index="i"
step="#javacast('float','0.01')#">
i=#i#<br>
</cfloop>
现在输出预期的六倍。
i=0.00999999977648
i=0.019999999553
i=0.0299999993294
i=0.0399999991059
i=0.0499999988824
i=0.0599999986589
然后,您可以在输出这些值时添加 NumberFormat()
函数以获得所需的输出。不确定您在这里需要的精度。您也可以使用邓肯的示例。
<cfloop from="#javacast('float','0.01')#"
to="#javacast('float','0.06')#"
index="i"
step="#javacast('float','0.01')#">
i=#NumberFormat(i,"9.99")#<br>
</cfloop>
输出:
i=0.01
i=0.02
i=0.03
i=0.04
i=0.05
i=0.06
关于coldfusion - 当步长为 0.01 到 0.06 时,CFloop 是否无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33081707/