开发者

Parsing a fraction to double

I want to parse a fraction stored in a string(e.g. "2/13") to a double. I can write the parsing code but my only question is where should this code go. Best would be if I could use double.Parse() function for this purpose. Is it possible to do it? If double.Parse() can't be used as it is how about writing an extension method? Or any other way?

I don't want to write a Fraction class becau开发者_高级运维se the conversion from the string representation of fraction to double is going to be a one time operation(when the user first enters it) and after that the fraction string will be discarded.


" ... after that the fraction string will be discarded."

You could make the fraction class static, with a static Parse Method that takes a string and returns a double.

public static class Fraction
{
   public static double Parse(string inValue)
   {
      // code to parse string 
      //  and return calculated value
   }
}

usage:

   double myvalue = Fraction.Parse("2/13");

Nothing is instantiated, nothing is discarded ...

This approach assumes of course, that you don't care to keep the original values (based on your mentioning in yr question that you wish to "throw away" the inital string value used to create the fraction).

If, otoh, you wanted to "hold on" to that state (the initial values of the two integers used to create the fraction), then a separate non-static class (actually a struct might be better in this case) would be a better way to go. Then you lose no precision, as future arithmetic operations using instances of this struct could be coded to use the two original exact integral state values stored in these fields instead of the slightly less accurate rounded double you got from the division operation.


It is not possible to override double.Parse() itself with an extension method, but you could create a double.ParseFraction() extension method instead. That seems a sensible way to do it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜