coldfusion-JavaCast浮动大幅度舍入

我计算总和,并将其放入使用Coldfusion中的POI库生成的Excel工作表中.如Java库所期望的那样,我总是调用setCellValue(JavaCast(“ float”,myVar)). .03使我知道了舍入错误.比铸造后通常已知的差异大得多.

<cfset s = 601761.66>
<cfoutput>
#s#<br>
#JavaCast( "float", s )#<br>
#LSNumberFormat( JavaCast( "float", s ), ".0000000" )#<br><br>
</cfoutput>

>第一行打印601761.66
>第二轮至601761.7
>但是,第三个会打印:601761,6875000,它等于601761,69,并且比我输入的值大0.03.

我知道,LSNumberFormat返回一个字符串.我称它为比较. POI似乎存储浮点值,Excel最终会像LSNumberFormat一样显示该值.

如何将值传递给setCellValue,该值与我的值如此接近,以至于至少十进制后的第二个数字正确取整?

最佳答案
简短答案:

使用double类型而不是float类型,即javacast(“ double”,value)

更长的答案:

Cell.setCellValue()方法实际上期望类型为Double(而不是Float). CF也是most numeric operations and functions使用的是Double.当将Float传递给这些方法时,它会隐式转换为Double.该转换(间接)导致意外结果.

原因是两者都为Float and Double are approximate types.但是,Double具有更高的精度:

float: The float data type is a single-precision 32-bit IEEE 754 floating point. …

double: The double data type is a double-precision 64-bit IEEE 754 floating point. …

因此,正如this thread所指出的(强调我的):

It’s not that you’re actually getting extra precision – it’s that the
float didn’t accurately represent the number you were aiming for
originally. The double is representing the original float accurately;
toString is showing the “extra” data which was already present.
… [When converted to a double, it] will have exactly the same value, but when you convert it to a string it will “trust” that it’s accurate to a higher precision, so won’t round off as early, and you’ll see the “extra digits” which were already there, but hidden from you

这就是为什么将“ 601761.66”和“ 601761.6875”都转换为浮点数时都将其四舍五入为“ 601761.7”,而将其转换为双精度时会显示为预期的原因.

<cfscript>
    value1 = "601761.66";
    value2 = "601761.6875";

    WriteOutput("<br>[Float] "& value1 &" = "& javacast("float", value1));
    WriteOutput("<br>[Float] "& value2 &" = "& javacast("float", value2));
    WriteOutput("<br>[Float=>Double] "& value1 &" = "& javacast("double", javacast("float", value1)));
    WriteOutput("<br>[Double] "& value1 &" = "& javacast("double", value1));
    WriteOutput("<br>[Double] "& value2 &" = "& javacast("double", value2));
</cfscript>

输出:

[Float] 601761.66 = 601761.7
[Float] 601761.6875 = 601761.7
[Float=>Double] 601761.66 = 601761.6875
[Double] 601761.66 = 601761.66
[Double] 601761.6875 = 601761.6875

注意:CF使用Float.toString()和Double.ToString()通过cfoutput / writeOutput / cfdump显示值.

转载注明原文:coldfusion-JavaCast浮动大幅度舍入 - 代码日志