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″).

<cffunctionname="displayFraction"output="false"access="public"returntype="string"hint="Generates a fraction from a decimal.">

<cfsetfraction = fraction & " #numerator#/#denominator#">

</cfif>

<cfreturnfraction>

</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!

2 thoughts on “Dynamic Fraction Display For ColdFusion”

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!

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!