Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Double as Fraction [closed]

Is there a library that will convert a Double to a String with the whole number, followed by a fraction?

For example

1.125 = 1 1/8

I am only looking for fractions to a 64th of an inch.

like image 635
Milhous Avatar asked Dec 18 '08 20:12

Milhous


2 Answers

Your problem is pretty simple, because you're assured the denominator will always divide 64. in C# (someone feel free to translate a Java version):

string ToMixedFraction(decimal x) 
{
    int whole = (int) x;
    int denominator = 64;
    int numerator = (int)( (x - whole) * denominator );

    if (numerator == 0) 
    {
        return whole.ToString();
    }
    while ( numerator % 2 == 0 ) // simplify fraction
    {
        numerator /= 2;
        denominator /=2;
    }
    return string.Format("{0} {1}/{2}", whole, numerator, denominator);
}

Bonus: Code Golf

public static string ToMixedFraction(decimal x) {
    int w = (int)x,
        n = (int)(x * 64) % 64,
        a = n & -n;
    return w + (n == 0 ? "" : " " + n / a + "/" + 64 / a);
}
like image 59
Jimmy Avatar answered Sep 20 '22 15:09

Jimmy


One problem you might run into is that not all fractional values can be represented by doubles. Even some values that look simple, like 0.1. Now on with the pseudocode algorithm. You would probably be best off determining the number of 64ths of an inch, but dividing the decimal portion by 0.015625. After that, you can reduce your fraction to the lowest common denominator. However, since you state inches, you may not want to use the smallest common denominator, but rather only values for which inches are usually represented, 2,4,8,16,32,64.

One thing to point out however, is that since you are using inches, if the values are all proper fractions of an inch, with a denominator of 2,4,8,16,32,64 then the value should never contain floating point errors, because the denominator is always a power of 2. However if your dataset had a value of .1 inch in there, then you would start to run into problems.

like image 39
Kibbee Avatar answered Sep 20 '22 15:09

Kibbee