ColdFusion offers several different methods for rounding, but none that allow rounding to a specific fraction/decimal.
Use the simple equation of "round( value/fraction ) * fraction" to round a number to a specific fraction/decimal.
Using a little basic math and ColdFusion's round() function, we can very easily round a number to a specific fraction/decimal:
<cfset fraction = 0.25 /> <cfset value = 3.37 /> <cfoutput>#(round( value/fraction ) * fraction )#</cfoutput>
This would round the value of
3.37 to
3.25. You can easily wrap this equation into a
re-usable UDF that offers a little more functionality:
<cfscript>
/**
* Rounds a number to the nearest fraction
*
* @param num The number to round. (Required)
* @param frac The fraction to round to. (Required)
*
* @return Returns a number.
*/
function roundToFraction(num, frac){
var result = ;
return round(num/frac) * frac;
}
</cfscript>
You can now round a number by doing:
<cfoutput>#roundToFraction(3.37, 0.25)#</cfoutput>
+