2

Is there a easy way to convert say 1.3333333 to say 1+1/3 in C#? There is code for just the fraction but not the whole number. Should I just pull that out before using the fraction?

Jacek
  • 11,661
  • 23
  • 69
  • 123
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341
  • Do you need exactly [continued fraction](http://en.wikipedia.org/wiki/Continued_fraction) – goGud Apr 16 '15 at 14:06

2 Answers2

1

I think it will be hard. Two reasons:

  1. A fraction can always be converted to a decimal number, but a decimal sometimes looses digits, so a exact roundtrip would be impossible. For example: Which number qualifies to be converted to 1/3?:

    • 0.33?
    • 0.333333?
    • 0.333333333333333333333333333333333333333333333333333333333333333333?
  2. Each decimal number can be converted to multible fractions. For example: 0.25 can be converted to:

    • 1/4
    • 2/8
    • 25/100

However, if you are open for some less exact solutions, try: Algorithm for simplifying decimal to fractions

Community
  • 1
  • 1
Martin Mulder
  • 12,642
  • 3
  • 25
  • 54
0

You should set max denominator for example 1 000 000 (one milione) and try to shorten. You have to aware of could lose precision

For example you have 1,450

  1. You take fraction part and multiple by your denominator, it is 450 000 / 1 000 000
  2. Then you find "greatest common divisor"
  3. Divide both part by divisor from previous point
  4. Finally you get your fraction 9/20
Jacek
  • 11,661
  • 23
  • 69
  • 123