hi tech id
hi tech id

Reputation: 111

How to adding a fraction with a whole..?

how to adding fraction with whole in C#..: 2 + 1 1/5 = ??

or

3 + 3/4 = ?? -----> it's just for example...:), it can be 3 + 2/3 or 4 + 6/7..

help please.. thank you all.. :)

Upvotes: 1

Views: 1283

Answers (3)

Eric Lippert
Eric Lippert

Reputation: 660377

Sure, no problem. Download the Microsoft Solver Foundation and use the Rational type to do arithmetic on fractional numbers.

Upvotes: 4

Javed Akram
Javed Akram

Reputation: 15354

You can change each fraction to its equivalent decimal value. And then operate them.

Remember whole fractions can be used as:

1 1/4         => 1 + 1/4
2 1/5 + 2 2/3 => 2 + 1/5 + 2 + 2/3      

Now, remember for data-type.

int i = 1/4;       // it will give 0 since i is int
decimal i = 1/4m   // ok, it will give  0.25;

Example:

decimal i = 2 + 1/5m + 2 + 2/3m;  //it will ok for  2 1/5 + 2 2/3


UPDATE

C# Code

decimal Fraction(string f)
    {
        var numbers = f.Split(' ', '+');
        decimal temp, result = 0.0m;
        decimal numerator, denominator;
        foreach (var str in numbers)
        {
            if (decimal.TryParse(str, out temp))
            {
                result += temp;
            }
            else if (str.Contains("/"))
            {
                var frac = str.Split('/');
                decimal.TryParse(frac[0], out numerator);
                decimal.TryParse(frac[1], out denominator);

                result += numerator / denominator;
            }
        }
        return result;
    }

Usage:

decimal d = Fraction("2 2/3 + 5/7 + 1 1/4");     //4.630952380952380952380952381

// put a space between whole and fraction value   => 1 1/2
// put a + sign to add numbers between them       => 1 2/3 + 2/3

[NOTE: this program is only for addition not for subtraction]

Upvotes: 3

Dave81
Dave81

Reputation: 3005

Wouldn't that be "2 + 6/5" or "16/5"? Correct me if I'm wrong but there is no fractions in c#. There is some open source projects for that though.

Upvotes: 0

Related Questions