Reputation: 981
Part of my job as an accounting associate requires me to assign expense groups to various items on invoices. For instance, if an office supply company sent us some goods I may have to separate copier paper from pens, and code those to separate expense groups.
Dividing amounts from like expense groups into the overall shipping and tax amounts was a tedious operation, but I decided that I could work smarter by writing a program which would adjust the amounts for me given the input: items[], shipping, tax. This is working like a charm and has really decreased my time needed to work on these tasks.
However, I want to implement an Excel-style functionality whereby I can have + and - operators in the text boxes that will allow me to easily add like items together on one line. (I.e. Pens, sharpies, notepads, which would all be on separate lines on an invoice, all need to be calculated and returned as one sum.)
I'm currently taking the txtValue.Text
and converting it to double to perform calculations. I would like to be able to parse that Text value and evaluate the statement entered. If I can glance at an invoice and type in 16.49+22.38+47.06
and know that everything will be fine when I hit my calculate button, then this is going to save me time adding them together on a calculator, for instance.
I wrote this once in VBA for Excel, which natively allows for that, but it just doesn't feel as good as something I custom-make.
Upvotes: 0
Views: 851
Reputation: 3189
string value = "1.2+5.3-1";
char[] delimiters = new char[] { '+', '-' };
string[] parts = value.Split(delimiters);
string[] signs = Regex.Split(value, "[0-9]|\\.");
This will give you an array of numbers (you'll need to convert them to double) and an array of the signs (there will be some empty elements aswell, you should ignore those.
Just iterate over them and use a switch do the actual mathematical operations.
Upvotes: 2
Reputation: 96
There are several ways to tackle this problem. This is a rough solution I came up with. There are probably a dozen more elegant ways to go about it.
public double Parse(string input)
{
char lastoperator = '0';
double result = 0;
for (int i = 0; i < input.Length; i++)
{
string temp = "";
if (char.IsDigit(input[i]) || input[i] == '.')
temp += input[i];
else if(input[i] == '+' || input[i] == '-')
{
double val;
if(double.TryParse(temp, out val))
{
if(lastoperator == '+')
result += val;
else if(lastoperator == '-')
result -= val;
else
result = val;
lastoperator = input[i];
temp = "";
}
//else error
}
else
continue;
}
return result;
}
Hope that helps.
Upvotes: 2