我正在编写一段ColdFusion代码来计算平均成绩点。如何将GPA格式化(四舍五入)到小数点后一位?
我尝试使用numberFormat,但没有得到预期的结果。GPA被四舍五入为最接近的整数。例如。当我的GPA为3.23时,函数会将其四舍五入为3.0,而不是3.2。
<cfdump var = "#numberFormat(totalgpa, '.0')#">例如。
当我的GPA是3.23时,预期结果应该是3.2;
当我的GPA是3.45时,预期结果应该是3.5;
当我的GPA是3.98时,预期结果应该是4.0;
发布于 2019-02-07 07:31:48
当涉及到舍入和数字精度时,我不再信任CF。下面是“Java方式”:
<cfoutput>
#roundWithScale(3.23, 1)# = 3.2<br>
#roundWithScale(3.45, 1)# = 3.5<br>
#roundWithScale(3.98, 1)# = 4.0<br>
</cfoutput>
<cffunction name="roundWithScale" access="public" output="false" returnType="numeric">
<cfargument name="value" type="numeric" required="true">
<cfargument name="scale" type="numeric" default="2">
<cfargument name="rounding" type="string" default="ROUND_HALF_UP">
<cfset LOCAL.BigDecimal = createObject("java", "java.math.BigDecimal")>
<cfset LOCAL.value = createObject("java", "java.math.BigDecimal").init(
toString(ARGUMENTS.value)
)>
<cfreturn LOCAL.value.setScale(
javaCast("int", ARGUMENTS.scale),
LOCAL.BigDecimal[ARGUMENTS.rounding]
)>
</cffunction>https://stackoverflow.com/questions/54563434
复制相似问题