Not yet rated

Problem

ColdFusion offers several different methods for rounding, but none that allow rounding to a specific fraction/decimal.

Solution

Use the simple equation of "round( value/fraction ) * fraction" to round a number to a specific fraction/decimal.

Detailed explanation

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>

+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes