Paul,
quite simple math --
1. multiple the double by the base - 32 in your case, to get the numerator.
2. set the denominator to 32.
3. use Euclid's algorithm to find GCD.
4. divide numerator and denominator by GCD...
See Knuth, Vol1, page 2 for details of Euclid's algorithm - it is a trivial
iterative search method
here is quick hack in case you don't have Knuth handy...
regards
roy fine
namespace GCDExample{
class Class1{
static int GCD(int numer, int denom){
while(true){
int rem = denom%numer;
if(rem == 0) return numer;
denom = numer;
numer = rem;
}
}
static void RunTest(double dbVal){
int numerator = (int)(dbVal * 32);
int denominator = 32;
int gcd = GCD(numerator,denominator);
numerator /= gcd;
denominator /= gcd;
Console.WriteLine("double val:{0}\n numerator: {1}\n denominator:
{2}\n\n",dbVal,numerator,denominator);
}
static void Main(string[] args){
RunTest(0.0625);
RunTest(0.09375);
RunTest(0.25);
RunTest(0.50);
RunTest(0.75);
RunTest(0.9375);
RunTest(0.96873);
RunTest(0.96874);
RunTest(0.96875);
RunTest(0.96876);
RunTest(0.96877);
RunTest(0.96878);
RunTest(0.96879);
RunTest(0.96880);
}
}
}
"paul gao via .NET 247" <an*******@dotnet247.com> wrote in message
news:%2****************@TK2MSFTNGP11.phx.gbl...
hi all.
In my program I need to convert a double number to string representation in
fraction format and vise versa. For example, convert 0.75 to string "3/4"
and convert string "1/2" to 0.5. The class will only need to handle numbers
that increment by 1/32. That is 1/32, 2/32, 3/32.... 31/32, 1. If the double
number is 0.28 which is between 1/4 and 9/32, the string should be 9/32(go
with the bigger number).
TIA
--------------------------------
From: paul gao
-----------------------
Posted by a user from .NET 247 (
http://www.dotnet247.com/)
<Id>ReuzASqUkECHu6connty0g==</Id>