What is up with this in ColdFusion's DecimalFormat() function? How do I get the correct result?

跟風遠走 提交于 2019-12-01 17:31:14

问题


<cfset number1 = 20.5/80 * 100 />
<cfset number2 = 18.125 />
<cfset number3 = 6.875 />

<cfoutput>
DecimalFormat(#number1#): #DecimalFormat(number1)#<br />
DecimalFormat(#number2#): #DecimalFormat(number2)#<br />
DecimalFormat(#number3#): #DecimalFormat(number3)#
</cfoutput>

OUTPUTS:

DecimalFormat(25.625): 25.62

DecimalFormat(18.125): 18.13

DecimalFormat(6.875): 6.88

RATHER THAN OUTPUTING:

DecimalFormat(25.625): 25.63

DecimalFormat(18.125): 18.13

DecimalFormat(6.875): 6.88

It seems that a variable that is the result of a mathematical calculation makes DecimalFormat() behave differently. Any quick fix, without digging into java?


回答1:


I think the problem is not DecimalFormat(), but the typical floating-point rounding errors.

see: PrecisionEvaluate()




回答2:


DecimalFormat is a formatting function. Not a Mathematical function. Its job is not to round your number for you, unfortunately CF lacks good mathematical functions for decimals so you will have to write your own.

Here is one someone wrote on the CF livedocs page for round():

 <cffunction name="roundDecimal" returntype="numeric"> 
     <cfargument name="num" type="numeric" required="yes"> 
     <cfargument name="decimal" type="numeric" default="2" required="no"> 

     <cfreturn round(num*10^decimal)/10^decimal /> 
  </cffunction>



回答3:


A quick fix would be to change line 1 to number1 = NumberFormat(20.5/80 * 100,'9.999')




回答4:


Please see the CF documentation NumberFormat and do a page search on round to see some specific information.



来源:https://stackoverflow.com/questions/1428173/what-is-up-with-this-in-coldfusions-decimalformat-function-how-do-i-get-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!