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!
This worked great – thanks for posting it. I had to make 2 small mods for my project. It allow for 1/16ths precision and better display (a space character was in the wrong place). Here they are:
To allow for 16th of an inch, change line to 5 to:
[cfset fractionPart = (numberFormat(formatThis,".9999") - int(formatThis)) * 100]
(setting precision to 4 places)
Then for better display, change line 18 to:
[cfset fraction = "#wholePart# "]
(adding a space)
… and line 24 to:
[cfset fraction = fraction & "#numerator#/#denominator#"]
(removing a space)
Glad you found this useful! Since I was using it for a recipe application, I had not really tested anything more precise than 18th, since most recipes don’t call for anything smaller than that. Thanks for posting your tweaks as well!