Content
Resources
To Do
Toolbox

 FractionsAsText

Synopsis

Converts decimal numbers to text as a fraction. Specify the base denominator (optional, defaults to 16ths) and a flag to specify if the smallest possible denominator is to be used (optional, defaults to True).

CODE
' FractionsAsText
' http://www.utteraccess.com/wiki/FractionsAsText
' Code courtesy of UtterAccess Wiki
'
' You are free to use this code in any application,
' provided this notice is left unchanged.
'
' rev  date                          brief descripton
' 1.0  2015-07-25
'
Public Function FractionsAsText(ByVal N As Double, Optional Ftn = 16, Optional SPD As Boolean = True) As String
' ********************************************************************************
' Any zero or positive fractional or whole number displayed as a fraction result in text
' ROUNDS DOWN to next lower fractional part being used - 1/16 is default, but can be any denominator
' Optional Denominator, defaults to sixteenths, but can be any.
' Optional SPD - smallest possible denominator is used. Defaults to True
' Typically
' FractionsAsText( 10.879, 32) returns 10-7/8
' FractionsAsText( 10.879, 32, False) returns 10-28/32
' FractionsAsText(.063,16) returns 1/16
' ********************************************************************************
If N &lt; (1 / Ftn) Then ' Rounds down to zero
FractionsAsText = "0"
Exit Function
End If
If Int(N) &lt;&gt; 0 Then ' Set up the (non-zero) integer part
FractionsAsText = Int(N)
Else
FractionsAsText = ""
End If
N = N - Int(N) ' Leaves just the fractional part
If SPD Then ' SPD - smallest possible denominator
Do While (Int(Ftn * N) Mod 2 = 0) And (Ftn Mod 2 = 0)
Ftn = Ftn / 2
Loop
End If
If N &gt;= (1 / Ftn) Then ' eliminates a result like 1-0/16
If FractionsAsText = "" Then ' eliminates a result like -1/16
FractionsAsText = Int(Ftn * N) & "/" & Ftn
Else ' Puts the '-' between
FractionsAsText = FractionsAsText & "-" & Int(Ftn * N) & "/" & Ftn
End If
End If
End Function