with: Erik Oosterwal
![]()
Custom Search
|
' ' Routine to convert decimal values to integer fractions. ' ' Written by: Erik Oosterwal ' Started on: November 9, 2005 ' Completed on: November 9, 2005 ' Dim intNumerator, intDenominator, intNegative As Long ' Declare integer variables as long ' integers. Dim dblFraction, dblDecimal, dblAccuracy As Double ' Declare floating point variables ' as double precision. dblDecimal = Val(txtDecimal) ' Get the desired decimal value from the ' front panel (VB Form). dblAccuracy = Val(txtAccuracy) ' Get the desired accuracy from the front ' panel (VB Form). Need to put a check ' in here to make sure the desired ' accuracy is not smaller than what the ' programming language can handle. For ' VB, this should be 1E-13. intNumerator = 0 ' Set the initial numerator value to 0. intDenominator = 1 ' Set the initial denominator value to 1. intNegative = 1 ' Set the negative value flag to positive. If dblDecimal < 0 Then intNegative = -1 ' If the desired decimal value is negative, ' then set the negative value flag to ' negative. dblFraction = 0 ' Set the fraction value to be 0/1. While Abs(dblFraction - dblDecimal) > dblAccuracy ' As long as we're still outside the ' desired accuracy, then... If Abs(dblFraction) > Abs(dblDecimal) Then ' If our fraction is too big, intDenominator = intDenominator + 1 ' increase the denominator Else ' Otherwise intNumerator = intNumerator + intNegative ' increase the numerator. End If dblFraction = intNumerator / intDenominator ' Set the new value of the fraction. Wend txtNumerator.Text = Str(intNumerator) ' Display the numerator and denominator txtDenominator.Text = Str(intDenominator) ' values on the front panel (VB Form).
You can also download a zip file that contains
an executable file that demonstrates this routine along with the Visual Basic
project.