Round decimal to fraction

G

Guest

How can you round a decimal to the next greatest 1/8 and display it as a
fraction? (I could probably figure it out, but I know there are a lot of you
smart people out there who already know how to do this)- thanks!
 
R

Rob Oldfield

This will do it for you...

Function to8(d As Double) As String
to8 = Round(d * 8 + 0.4999999999, 0) & "/8"
End Function

....while this will reduce any fraction...e.g. from 12/8 to 3/2...

Function reduce(t)
If IsNull(t) Then
reduce = ""
Exit Function
End If
Dim num As Long, den As Long, pos As Integer
pos = InStr(t, "/")
If pos = 0 Then
reduce = t
Exit Function
End If
num = CLng(Left(t, pos - 1))
den = CLng(Mid(t, pos + 1))
Dim i As Long
Dim maxfactor As Long
maxfactor = num
If Int(den / 2) < maxfactor Then
maxfactor = Int(den / 2)
End If
For i = maxfactor To 2 Step -1
If num Mod i = 0 And den Mod i = 0 Then
num = num / i
den = den / i
Exit For
End If
Next
If num Mod den = 0 Then
reduce = num / den
Else
reduce = CStr(num) & "/" & CStr(den)
End If
End Function

Needs some error handling and probably some exceptions along the lines of
divisions by 0 that I'm missing somewhere.
 
G

Guest

Thank you very much!

Rob Oldfield said:
This will do it for you...

Function to8(d As Double) As String
to8 = Round(d * 8 + 0.4999999999, 0) & "/8"
End Function

....while this will reduce any fraction...e.g. from 12/8 to 3/2...

Function reduce(t)
If IsNull(t) Then
reduce = ""
Exit Function
End If
Dim num As Long, den As Long, pos As Integer
pos = InStr(t, "/")
If pos = 0 Then
reduce = t
Exit Function
End If
num = CLng(Left(t, pos - 1))
den = CLng(Mid(t, pos + 1))
Dim i As Long
Dim maxfactor As Long
maxfactor = num
If Int(den / 2) < maxfactor Then
maxfactor = Int(den / 2)
End If
For i = maxfactor To 2 Step -1
If num Mod i = 0 And den Mod i = 0 Then
num = num / i
den = den / i
Exit For
End If
Next
If num Mod den = 0 Then
reduce = num / den
Else
reduce = CStr(num) & "/" & CStr(den)
End If
End Function

Needs some error handling and probably some exceptions along the lines of
divisions by 0 that I'm missing somewhere.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top