Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a text fraction to a decimal

Tags:

c#

Similar to this question just in C# instead of JavaScript. I couldn't find anything for C# while searching

I have a text box that will take a quantity, which is later stored as a double in a database. However it is possible that some quantities will be entered as string fractions e.g 1/2 for 0.5. I want to be able to convert these to decimal before storing them to the database (being able to also convert back would be nice but not necessary). I want to be able to handle both fractions and mixed numbers e.g. 2 1/2 is saved as 2.5

Anybody know a way of doing this?

like image 451
J.B Avatar asked Dec 16 '12 17:12

J.B


People also ask

How do I convert fractions to decimals?

To convert a fraction to a decimal, we'll just divide the numerator...by the denominator. In our example, we'll divide 1 by 4. 1 divided by 4 equals 0. To keep dividing, we'll add a decimal point and a zero after the 1.

How do you convert text to a decimal?

In order to use this ascii text to decimal converter tool, type an ascii value like "love" to get "108 111 118 101" and then hit the Convert button. This is the way you can convert up to 128 ascii text to decimal characters.

What is 7/8 as a decimal?

7 divided by 8 or 7/8 is equal to 7 divided by 8, which is equal to 0.875.


2 Answers

Try splitting it on the space and slash, something like:

double FractionToDouble(string fraction) {
    double result;

    if(double.TryParse(fraction, out result)) {
        return result;
    }

    string[] split = fraction.Split(new char[] { ' ', '/' });

    if(split.Length == 2 || split.Length == 3) {
        int a, b;

        if(int.TryParse(split[0], out a) && int.TryParse(split[1], out b)) {
            if(split.Length == 2) {
                return (double)a / b;
            }

            int c;

            if(int.TryParse(split[2], out c)) {
                return a + (double)b / c;
            }
        }
    }

    throw new FormatException("Not a valid fraction.");
}

Hey, it worked! Remember to check for a division by zero, too. You'll get Infinity, -Infinity, or NaN as a result.

like image 144
Ry- Avatar answered Oct 17 '22 09:10

Ry-


And here is yet one more solution, but with a bit more seamless an integration:

public class FractionalNumber
{
    public Double Result
    {
        get { return this.result; }
        private set { this.result = value; }
    }
    private Double result;

    public FractionalNumber(String input)
    {
        this.Result = this.Parse(input);
    }

    private Double Parse(String input)
    {
        input = (input ?? String.Empty).Trim();
        if (String.IsNullOrEmpty(input))
        {
            throw new ArgumentNullException("input");
        }

        // standard decimal number (e.g. 1.125)
        if (input.IndexOf('.') != -1 || (input.IndexOf(' ') == -1 && input.IndexOf('/') == -1 && input.IndexOf('\\') == -1))
        {
            Double result;
            if (Double.TryParse(input, out result))
            {
                return result;
            }
        }

        String[] parts = input.Split(new[] { ' ', '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);

        // stand-off fractional (e.g. 7/8)
        if (input.IndexOf(' ') == -1 && parts.Length == 2)
        {
            Double num, den;
            if (Double.TryParse(parts[0], out num) && Double.TryParse(parts[1], out den))
            {
                return num / den;
            }
        }

        // Number and fraction (e.g. 2 1/2)
        if (parts.Length == 3)
        {
            Double whole, num, den;
            if (Double.TryParse(parts[0], out whole) && Double.TryParse(parts[1], out num) && Double.TryParse(parts[2], out den))
            {
                return whole + (num / den);
            }
        }

        // Bogus / unable to parse
        return Double.NaN;
    }

    public override string ToString()
    {
        return this.Result.ToString();
    }

    public static implicit operator Double(FractionalNumber number)
    {
        return number.Result;
    }
}

And because it implements the implicit operator, it can be used simply by:

Double number = new FractionalNumber("3 1/2");

Anything that can't be parsed returns the Double constant Double.NaN. Without getting in to a laundry list of possible inputs, this worked with some basics. Feel free to tweak the class to fit your needs.

like image 23
Brad Christie Avatar answered Oct 17 '22 09:10

Brad Christie