Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Fraction to Double

Tags:

string

c#

asp.net

I need a function to parse a user inputs of numbers to doubles. I cannot do anything client side or change how the input comes in.

Input       | Desired Output
"9"         | 9
"9 3/4"     | 9.75
" 9  1/ 2 " | 9.5
"9 .25"     | 9.25
"9,000 1/3" | 9000.33
"1/4"       | .25

I saw this post, but it uses Python, I was just wondering if anybody knew any fancy C# ways of handling this before I spend time to write my own.

like image 349
Greg Avatar asked Jan 06 '12 17:01

Greg


2 Answers

I would use regular expressions for this one:

Regex re = new Regex(@"^\s*(\d+)(\s*\.(\d*)|\s+(\d+)\s*/\s*(\d+))?\s*$");
string str = " 9  1/ 2 ";
Match m = re.Match(str);
double val = m.Groups[1].Success ? double.Parse(m.Groups[1].Value) : 0.0;

if(m.Groups[3].Success) {
    val += double.Parse("0." + m.Groups[3].Value);
} else {
    val += double.Parse(m.Groups[4].Value) / double.Parse(m.Groups[5].Value);
}

Untested, as of yet, but I think it should work.

Here's a demo, and here's another demo.

like image 110
Ry- Avatar answered Oct 05 '22 23:10

Ry-


There is nothing built in the BCL that will do this, but there are plenty of existing mathematical expression parsers that will (though this may be over the top for this specific situation).

Writing one yourself, for the limited use cases you have posted shouldn't be difficult.

like image 21
Oded Avatar answered Oct 05 '22 23:10

Oded