Dynamic Fraction Display For ColdFusion
Ever want to store a value in a database as a decimal value, but then display that value on your ColdFusion website as a fraction. Well, now you can!
The following function (cut out of a more general CFC) does just that for fractions as precise as 1/100, and will handle the whole number parts as well (i.e. displaying "1.25" as "1 1/4").
<cffunction name="displayFraction" output="false" access="public" returntype="string" hint="Generates a fraction from a decimal.">
<cfargument name="formatThis" type="Numeric" required="true">
<cfset wholePart = int(formatThis)>
<cfset fractionPart = (numberFormat(formatThis,".999") - int(formatThis)) * 100>
<cfif fractionPart NEQ 0>
<cfloop from="2" to="100" index="d">
<cfif (round(fractionPart * d) MOD 100) EQ 0>
<cfset denominator = d>
<cfset numerator = round(fractionPart * d) / 100>
<cfbreak>
</cfif>
</cfloop>
</cfif>
<cfif wholePart GT 0>
<cfset fraction = "#wholePart#">
<cfelse>
<cfset fraction = "">
</cfif>
<cfif fractionPart NEQ 0>
<cfset fraction = fraction & " #numerator#/#denominator#">
</cfif>
<cfreturn fraction>
</cffunction>
I wrote it for a recipe storage application for personal use, and thought others might find it useful as well. If you do find a good way to use it, feel free to drop me a line!




There are no comments for this entry.
[Add Comment]