UtterAccess HomeUtterAccess Wiki

Welcome Guest ( Log In | Register )

Custom Search
Edit Discussion
> 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://sbp.ghubbell.com/wiki/FractionsAsText
' Code courtesy of UtterAccess Wiki
' Licensed under Creative Commons License
' http://creativecommons.org/licenses/by-sa/3.0/
'
' 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 < (1 / Ftn) Then ' Rounds down to zero
       FractionsAsText = "0"
       Exit Function
   End If
   If Int(N) <> 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 >= (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

Creative Commons License
FractionsAsText by UtterAccess Wiki is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
Editing and revision of the content is freely encouraged; for details, see Expected Usage.

Edit Discussion
Custom Search
Thank you for your support!
This page has been accessed 1,079 times.  This page was last modified 03:23, 27 July 2015 by merlenicholson.   Disclaimers