fork(1) download
  1. using System;
  2.  
  3. public class Test
  4. {
  5. public static void Main()
  6. {
  7. foreach (var test in new[]{ "1", "1.5", "2.125", "3 7/8", "5/16" })
  8. {
  9. Console.WriteLine("{0,-5} = {1:0.000}", test, new FractionalNumber(test));
  10. }
  11. }
  12. }
  13.  
  14. public class FractionalNumber
  15. {
  16. public Double Result
  17. {
  18. get { return this.result; }
  19. private set { this.result = value; }
  20. }
  21. private Double result;
  22.  
  23. public FractionalNumber(String input)
  24. {
  25. this.Result = this.Parse(input);
  26. }
  27.  
  28. private Double Parse(String input)
  29. {
  30. input = (input ?? String.Empty).Trim();
  31. if (String.IsNullOrEmpty(input))
  32. {
  33. throw new ArgumentNullException("input");
  34. }
  35.  
  36. // standard decimal number (e.g. 1.125)
  37. if (input.IndexOf('.') != -1 || (input.IndexOf(' ') == -1 && input.IndexOf('/') == -1 && input.IndexOf('\\') == -1))
  38. {
  39. Double result;
  40. if (Double.TryParse(input, out result))
  41. {
  42. return result;
  43. }
  44. }
  45.  
  46. String[] parts = input.Split(new[] { ' ', '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
  47.  
  48. // stand-off fractional (e.g. 7/8)
  49. if (input.IndexOf(' ') == -1 && parts.Length == 2)
  50. {
  51. Double num, den;
  52. if (Double.TryParse(parts[0], out num) && Double.TryParse(parts[1], out den))
  53. {
  54. return num / den;
  55. }
  56. }
  57.  
  58. // Number and fraction (e.g. 2 1/2)
  59. if (parts.Length == 3)
  60. {
  61. Double whole, num, den;
  62. if (Double.TryParse(parts[0], out whole) && Double.TryParse(parts[1], out num) && Double.TryParse(parts[2], out den))
  63. {
  64. return whole + (num / den);
  65. }
  66. }
  67.  
  68. // Bogus / unable to parse
  69. return Double.NaN;
  70. }
  71.  
  72. public override string ToString()
  73. {
  74. return this.Result.ToString();
  75. }
  76.  
  77. public static implicit operator Double(FractionalNumber number)
  78. {
  79. return number.Result;
  80. }
  81. }
Success #stdin #stdout 0.04s 34736KB
stdin
Standard input is empty
stdout
1     = 1
1.5   = 1.5
2.125 = 2.125
3 7/8 = 3.875
5/16  = 0.3125