how to dynamically generate a formula and solive it by selecting multiple rows using linq - c#

hi guys i have an array called tblCeMaintMatrix.ToArray()) with a result of :
[0]: { xValue = 0, Operator = 43 '+' }
[1]: { xValue = 1, Operator = 43 '+' }
[2]: { xValue = 12, Operator = 45 '-' }
i made a foreach loop to solve this however i encountered some errors. I think i confused the logic for this..
foreach (var a in tblCeMaintMatrix.ToArray())
{
{
value = operate((a.Operator).ToString(),a.xValue.Value );
}
decimal value2 = value;
}
private decimal operate(String a, Decimal value)
{
Decimal Value = 0;
if (a == "+")
{
Value = value + value;
}
if (a == "-")
{
Value= value - value;
}
if (a == "*")
{
Value = value * value;
}
if (a == "/")
{
Value = value / value;
}
return Value;
}
my problem is that
a) what is does is this :
0 + 0 = 0
1 + 1 = 2
12 - 12 = 0
instead of 0 + 1 -12.
b) it doesnt retain the value.
how can i modify this to solve the problem? thanks

Non-tested code, I wish it's correct..
decimal result = 0;
foreach (var a in tblCeMaintMatrix.ToArray())
{
{
result = operate((a.Operator).ToString(),a.xValue.Value,result);
}
}
private decimal operate(String a, Decimal value, Decimal result)
{
switch (a)
{
case "+": result += value; break;
case "-": result -= value; break;
case "*": result *= value; break;
case "/": result /= value; break;
default: result = value; break;
}
return result;
}
EDIT to ignore the first operator, I think you need to set your first operator to empty, like:
[0]: { xValue = 0, Operator = '' }
[1]: { xValue = 1, Operator = 43 '+' }
[2]: { xValue = 12, Operator = 45 '-' }
and see the modified Operate method.

Right now you are only passing a single value to your operate method, and using it as both operands. You need to also pass the running total of your code to the function:
Decimal total = 0;
foreach (var a in tblCeMaintMatrix.ToArray())
{
{
total = operate((a.Operator).ToString(),total, a.xValue.Value );
}
decimal value2 = value;
}
private decimal operate(String a, Decimal left, Decimal right)
{
Decimal Value = 0;
if (a == "+")
{
Value = left + right;
}
if (a == "-")
{
Value= left - right;
}
if (a == "*")
{
Value = left * right;
}
if (a == "/")
{
Value = left / right;
}
return Value;
}
It's not clear what's your using value2 to represent in your original function.

Related

C# - Check if entered string is a Integer or not

i want to check if entered string is a Integer or not for example
12 = True
+12 = True
-5 = True
4.4 = False
4as = False
I make it using int.TryParse but what I want is to using ASCII without using int.TryParse
string str;
int strint;
int strintoA;
bool flag = false;
while (flag == false)
{
Console.Write("Enter a Number : ");
str = Console.ReadLine();
flag = int.TryParse(str, out strint);
if (flag == false)
{
Console.WriteLine("Please Enter Numbers Only.");
}
else
{
strintoA = strint;
Console.WriteLine("Entered String: " + str + " is a Number!" );
break;
}
}
Console.ReadKey();
You could also use regular expressions:
var regex = new Regex(#"^[-+]?\d+$");
var str = Console.ReadLine();
if (regex.IsMatch(str))
{
Console.WriteLine($"{str} is a number!");
}
check the first char for -|+|digit, check rest isDigit
for (int i = 0; i < str.Length; i++)
{
var c = str[i];
if (i == 0)
{
if (!(c == '+' || c == '-' || char.IsDigit(c)) {
return false;
}
}
if (!char.IsDigit(c)) return false;
}
return true;
why dont use:
if(intString[0] == '+' || intString[0] == '-') intString = intString.Substring(1, intString.Length - 1);
bool isNumber = intString.All(char.IsDigit);
Not sure why you don't want to use int.TryParse but the following code should do:
static bool IsValidInteger(string s)
{
var leadingSignSeen = false;
var digitSeen = false;
var toParse = s.Trim();
foreach (var c in toParse)
{
if (c == ' ')
{
if (digitSeen)
return false;
}
else if (c == '+' || c == '-')
{
if (leadingSignSeen || digitSeen)
return false;
leadingSignSeen = true;
}
else if (!char.IsDigit(c))
return false;
else
{
digitSeen = true;
}
}
return true;
}
This will accept any integer with leading sign and leading and trailing spaces. Whitespaces between leading sign and digits are also accepted.
FYI: You can refactor your code to simplify it for exactly the same functional output:
void Main()
{
int result;
Console.Write("Enter a Number : ");
while (!int.TryParse(Console.ReadLine(), out result))
{
Console.WriteLine("Please Enter Numbers Only.");
Console.Write("Enter a Number : ");
}
Console.WriteLine($"Entered String: {result} is a Number!");
Console.ReadKey();
}
If you have a good reason to not use int.TryParse (e.g. it's lacking some functionality, or this is an exercise where you've been asked to write your own) you could use the above replacing int.TryParse with a call to IsNumericCustom, assuming the below signature (or change type int to whatever data type you need to handle).
public bool IsNumericCustom(string input, out int output)
{
//...
}
Or if you only care about whether the value's numeric and not the parsed value:
void Main()
{
string result;
Console.Write("Enter a Number : ");
//while (!int.TryParse((result = Console.ReadLine()), out _))
while (!IsNumericCustom((result = Console.ReadLine()))
{
Console.WriteLine("Please Enter Numbers Only.");
Console.Write("Enter a Number : ");
}
Console.WriteLine($"Entered String: {result} is a Number!");
Console.ReadKey();
}
public bool IsNumericCustom(string input)
{
//...
}
As for the logic in the IsNumericCustom, it really depends on what you're hoping to achieve / why int.TryParse / decimal.TryParse etc aren't appropriate. Here's a couple of implementations (using different function names).
using System.Text.RegularExpressions; //https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=netframework-4.7.2
//...
readonly Regex isNumeric = new Regex("^[+-]?\d*\.?\d*$", RegexOptions.Compiled); //treat "." as "0.0", ".9" as "0.9", etc
readonly Regex isInteger = new Regex("^[+-]?\d+$", RegexOptions.Compiled); //requires at least 1 digit; i.e. "" is not "0"
readonly Regex isIntegerLike = new Regex("^[+-]?\d*\.?\0*$", RegexOptions.Compiled); //same as integer, only 12.0 is treated as 12, whilst 12.1 is invalid; i.e. only an integer if we can remove digits after the decimal point without truncating the value.
//...
public bool IsNumeric(string input)
{
return isNumeric.IsMatch(input); //if you'd wanted 4.4 to be true, use this
}
public bool IsInteger(string input)
{
return isInteger.IsMatch(input); //as you want 4.4 to be false, use this
}
public bool IsIntegerLike(string input)
{
return isIntegerLike.IsMatch(input); //4.4 is false, but both 4 and 4.0 are true
}
From your requirements it appears that you want to use ASCII code in order to assert whether the string entered is numeric or not.
This is the code I have come up with:
string str;
var index = 1;
int strintoA = 0;
bool isNegative = false;
//ASCII list of numbers and signs
List<int> allowedValues = new List<int> { 43, 45, 48, 49, 50, 51, 52, 53, 54, 55, 56,
57 };
bool flag = false;
while (!flag)
{
Console.WriteLine("Enter a Number : ");
str = Console.ReadLine();
if (str.Count(item => allowedValues.Contains((int)item)) == str.Count())
{
foreach (var item in str.Reverse())
{
if (item != 43 && item != 45)
{
strintoA += index * (item - 48);
index = index * 10;
}
else if(item == 45)
{
isNegative = true;
}
}
if(isNegative)
{
strintoA *= -1;
}
Console.WriteLine("Entered String: " + str + " is a Number!");
flag = true;
}
else
{
Console.WriteLine("Please Enter Numbers Only.");
}
}
Console.ReadKey();
}
The allowedValues list contains the ASCII representation of numeric values and allowed signs(+ and -). The foreach loop will regenerates the int value inserted.
Hope it helps.

Library for calculating GTIN from EAN-13 barcode

I am creating an XML from a backend that is supposed to be fed into a GDSN datapool. The company has a very old backend which only has their own PLU number and barcode attached to every item. What I know is that (at least here in Iceland) most GTIN are the EAN-13 barcode with a padded 0 at the front although this is not always the case. Do you know of a library that could check if a GTIN is correct i.e. would calculate the check digit?
I am using a windows form and am using C#.
First to validate what you want to do:
https://www.gs1.org/services/check-digit-calculator
Then you have 2 possibilities for GTIN since it must be 14 digits long.
The case you described, then you pad a 0 on the left
A GTIN with right length is provided directly (which is possible and left digit will not be 0)
Here is a quick example on how you can check this, based on the fact you know the gtin string only contains digits:
public Boolean ValidateGTIN(string gtin)
{
string tmpGTIN = gtin;
if (tmpGTIN.Length < 13)
{
Console.Write("GTIN code is invalid (should be at least 13 digits long)");
return false;
}
else if (tmpGTIN.Length == 13)
{
tmpGTIN = "0" + gtin;
}
// Now that you have a GTIN with 14 digits, you can check the checksum
Boolean IsValid = false;
int Sum = 0;
int EvenSum = 0;
int CurrentDigit = 0;
for (int pos = 0; pos <= 12; ++pos)
{
Int32.TryParse(tmpGTIN[pos].ToString(), out CurrentDigit);
if (pos % 2 == 0)
{
EvenSum += CurrentDigit;
}
else
{
Sum += CurrentDigit;
}
}
Sum += 3 * EvenSum;
Int32.TryParse(tmpGTIN[13].ToString(), out CurrentDigit);
IsValid = ((10 - (Sum % 10)) % 10) == CurrentDigit;
if (!IsValid)
{
Console.Write("GTIN code is invalid (wrong checksum)");
}
return IsValid;
}
Thanks for that. This is almost there. I would like to take it a step further - I am going to copy your code and add a little:
//First create a function only for validating
//This is your code to almost all - variable names change
public Boolean validateGTIN(string gtin)
{
Boolean IsValid = false;
int Sum = 0;
int EvenSum = 0;
int CurrentDigit = 0;
for (int pos = 0; pos <= 12; ++pos)
{
Int32.TryParse(gtin[pos].ToString(), out CurrentDigit);
if (pos % 2 == 0)
{
EvenSum += CurrentDigit;
}
else
{
Sum += CurrentDigit;
}
}
Sum += 3 * EvenSum;
Int32.TryParse(GTIN[13].ToString(), out CurrentDigit);
IsValid = ((10 - (Sum % 10)) % 10) == CurrentDigit;
if (!IsValid)
{
Console.Write("GTIN code is invalid (wrong checksum)");
}
return IsValid;
}
//Here we change quite a bit to accommodate for edge cases:
//We return a string which is the GTIN fully formed or we throw and exception.
public String createGTIN(string bcFromBackend)
{
string barcodeStr = bcFromBackend;
//Here we check if the barcode supplied has fewer than 13 digits
if (barcodeStr.Length < 13)
{
throw new System.ArgumentException("Barcode not an EAN-13
barcode");
}
//If the barcode is of length 13 we start feeding the value with a padded 0
//into our validate fuction if it returns false then we pad with 1 and so on
//until we get to 9. It then throws an error if not valid
else if (barcodeStr.Length == 13)
{
if(validateGTIN("0"+ barcodeStr))
{
return "0" + barcodeStr;
}
else if(validateGTIN("1" + barcodeStr))
{
return "1" + barcodeStr;
}
else if(validateGTIN("2" + barcodeStr))
{
return "2" + barcodeStr;
}
else if(validateGTIN("3" + barcodeStr))
{
return "3" + barcodeStr;
}
else if(validateGTIN("4" + barcodeStr))
{
return "4" + barcodeStr;
}
else if(validateGTIN("4" + barcodeStr))
{
return "4" + barcodeStr;
}
else if(validateGTIN("5" + barcodeStr))
{
return "5" + barcodeStr;
}
else if(validateGTIN("6" + barcodeStr))
{
return "6" + barcodeStr;
}
else if(validateGTIN("7" + barcodeStr))
{
return "7" + barcodeStr;
}
else if(validateGTIN("8" + barcodeStr))
{
return "8" + barcodeStr;
}
else if(validateGTIN("9" + barcodeStr))
{
return "9" + barcodeStr;
} else {
throw new System.InvalidOperationException("Unable to create valid
GTIN from given barcode")
}
}
//Lastly if the barcode is of length 14 we try with this value. Else throw
//error
else if(barcodeStr.Length == 14)
{
if(validateGTIN(barcodeStr)
{
return barcodeStr;
}
else
{
throw new System.InvalidOperationException("Unable to create valid
GTIN from given barcode");
}
}
Hopefully this makes sense. I have not sent the code through testing as I don't have my IDE on my current computer installed. Is

C# Looping Messagebox for Exception

Looping Messagebox!!
I have a looping Messagebox after an error occurs and im wondering how to fix it. I have tried returning the Calculate() method and i think that's the problem, but im not sure.
namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public int division = 0;
private void Form1_Load(object sender, EventArgs e)
{
}
private decimal Calculate()
{
// This array is to hold the logical operators
string[] allowed = { "+", "-", "*", "/" };
// If the right operator is selceted then perform the action and return result
if (operate.Text == "+")
{
decimal division = Convert.ToDecimal(operand1.Text) + Convert.ToDecimal(operand2.Text);
}
else if (operate.Text == "-")
{
decimal division = Convert.ToDecimal(operand1.Text) - Convert.ToDecimal(operand2.Text);
}
else if (operate.Text == "*")
{
decimal division = Convert.ToDecimal(operand1.Text) * Convert.ToDecimal(operand2.Text);
}
else if (operate.Text == "/")
{
decimal division = (Convert.ToDecimal(operand1.Text) / Convert.ToDecimal(operand2.Text));
}
// if the operator is not something within the array then display message
else if (!allowed.Contains(operate.Text))
{
string msg = string.Format("Not a valid operater {0}Please Enter one of the Following:{0}{1}"
, Environment.NewLine, string.Join(Environment.NewLine, allowed));
MessageBox.Show(msg);
operate.Text = "";
}
return Calculate();
}
Try
private decimal Calculate()
{
// This array is to hold the logical operators
string[] allowed = { "+", "-", "*", "/" };
decimal result = 0m;
// If the right operator is selected then perform the action and return result
if (operate.Text == "+")
{
result = Convert.ToDecimal(operand1.Text) + Convert.ToDecimal(operand2.Text);
}
else if (operate.Text == "-")
{
result = Convert.ToDecimal(operand1.Text) - Convert.ToDecimal(operand2.Text);
}
else if (operate.Text == "*")
{
result = Convert.ToDecimal(operand1.Text) * Convert.ToDecimal(operand2.Text);
}
else if (operate.Text == "/")
{
result = (Convert.ToDecimal(operand1.Text) / Convert.ToDecimal(operand2.Text));
}
// if the operator is not something within the array then display message
else if (!allowed.Contains(operate.Text))
{
string msg = string.Format("Not a valid operater {0}Please Enter one of the Following:{0}{1}"
, Environment.NewLine, string.Join(Environment.NewLine, allowed));
MessageBox.Show(msg);
operate.Text = "";
}
return result;
}
// Try this
private void button1_Click(object sender, EventArgs e)
{
result.Text = Calculate().ToString();
}
private decimal Calculate() {
decimal division = 0;
// This array is to hold the logical operators
string[] allowed = { "+", "-", "*", "/" };
// If the right operator is selceted then perform the action and return result
if (operate.Text == "+")
{
division = Convert.ToDecimal(operand1.Text) + Convert.ToDecimal(operand2.Text);
}
else if (operate.Text == "-")
{
division = Convert.ToDecimal(operand1.Text) - Convert.ToDecimal(operand2.Text);
}
else if (operate.Text == "*")
{
division = Convert.ToDecimal(operand1.Text) * Convert.ToDecimal(operand2.Text);
}
else if (operate.Text == "/")
{
division = (Convert.ToDecimal(operand1.Text) / Convert.ToDecimal(operand2.Text));
}
// if the operator is not something within the array then display message
else if (!allowed.Contains(operate.Text))
{
string msg = string.Format("Not a valid operater {0}Please Enter one of the Following:{0}{1}"
, Environment.NewLine, string.Join(Environment.NewLine, allowed));
MessageBox.Show(msg);
operate.Text = "";
}
return division;
}
}

i want make math operation with one button C#

i want make math operation with one button and textbox , when type on textbox operation like 25+5+-10+7 and press on button show me result
i am trying do this but i can not.
in this code i make for each char in textbox and i want store 25 in firstvalue parameter and + in op parameter and 5 in secondvalue parameter
and make operation 25+5=30 and store it in firstvalue parameter and store +- in op , 10 in secondvalue and make operation ,store it in firstvalue ....and so on until length of string .
but i do not know where and how store second value
private void button1_Click(object sender, EventArgs e)
{
string allValue = textBox1.Text;
int firstValue=0;
int secondValue=0;
string first = string.Empty;
string op = string.Empty;
foreach (char item in allValue)
{
if (char.IsNumber(item))
{
first += item;
}
else if(item=='+' || item=='-' || item=='*' || item=='/')
{
firstValue = Int32.Parse(first);
op += item;
first = "";
switch (op)
{
case "+":
firstValue = firstValue + secondValue;
break;
case "-":
firstValue = firstValue - secondValue;
break;
case "+-":
firstValue = firstValue +- secondValue;
break;
case "*":
firstValue = firstValue * secondValue;
break;
case "/":
firstValue = firstValue / secondValue;
break;
}
}
}
MessageBox.Show(firstValue.ToString());
}
If you want to parse the string from beginning to end and do the calculations during the parsing, then you can't do the calculation between two values until you have both operands. That means that you have to wait until you find the second operator (or the end of the string) until you can do the calculation for the first operator.
When you parse the number, put that in the secondValue variable. If it's the first value then just move it to firstValue and continue to get another value, otherwise do the calculation with the two values that you have according to the previous operator.
To include the last calculation you can loop one step more than the last character in the string. That allows your loop to run one more time after the last value, and you can do that last calculation. It requires a few more checks though, so that you don't actually try to read from that position outside the string.
To handle negative values you should include that in the value, not using a +- operator. Otherwise you would also need --, *- and /- operators.
Example (not tested):
private void button1_Click(object sender, EventArgs e) {
string allValue = textBox1.Text;
int firstValue = 0;
int secondValue = 0;
string second = string.Empty;
string op = string.Empty;
for (int i = 0; i <= allValue.Length; i++) {
if (i < allValue.Length && (Char.IsNumber(allValue[i]) || (char == '-' && second.Length == 0))) {
second += allValue[i];
} else if (i == allValue.Length || "+-*/".indexOf(allValue[i]) != -1) {
secondValue = Int32.Parse(second);
if (op.Length > 0) {
switch (op) {
case "+": firstValue += secondValue; break;
case "-": firstValue -= secondValue; break;
case "*": firstValue *= secondValue; break;
case "/": firstValue /= secondValue; break;
}
} else {
firstValue = secondValue;
}
if (i < allValue.Length) {
op = allValue[i].ToString();
}
second = "";
} else {
// illegal formula
}
}
MessageBox.Show(firstValue.ToString());
}
Note: This calculates strictly from left to right and does not handle priority, e.g. 1+2*3 is evaluated as (1+2)*3, not the 1+(2*3) that is normally used.
You can use the NCalc library. You would use it like this:
NCalc.Expression e = new NCalc.Expression(textBox1.Text);
double value = e.Evaluate();
// Next, do something with your evaluated value.
Would this work for you? As mentioned in earlier answers this does not pay regard to the order of operations and there is a lot of other error checking that should likely be done.
using System.Text.RegularExpressions;
private void button1_Click(object sender, EventArgs e)
{
MatchCollection values = Regex.Matches(textBox1.Text, "[0-9]+");
MatchCollection operations = Regex.Matches(textBox1.Text, #"[\/\*\+-]");
if (values.Count == operations.Count + 1)
{
int total = int.Parse(values[0].Value);
if (operations.Count > 0)
{
for (int index = 1; index < values.Count; index++)
{
int value = int.Parse(values[index].Value);
switch (operations[index - 1].Value)
{
case "+":
total += value;
break;
case "-":
total -= value;
break;
case "/":
total /= value;
break;
case "*":
total *= value;
break;
}
}
}
MessageBox.Show(total.ToString());
}
}
Doing all the things from scratch is not easy. In my simplified answer I'll presume your operators are only +-*/ (including their precedence).
Reference: How to evaluate an infix expression in just one scan using stacks?
First you should parse the input string... My way would be
public enum TokenType
{
Operator,
Operand
}
public class Token
{
public string Value { get; set; }
public TokenType Type { get; set; }
public override string ToString()
{
return Type + " " + Value;
}
}
IEnumerable<Token> Parse(string input)
{
return Regex.Matches(input, #"(?<value>\d+)|(?<type>[\+\-\*\/\(\)])").Cast<Match>()
.Select(m => m.Groups["value"].Success
? new Token() { Value = m.Groups["value"].Value, Type = TokenType.Operand }
: new Token() { Value = m.Groups["type"].Value, Type = TokenType.Operator });
}
This Parse method will return all the operators and operands in your expression.
The next step would be to evaluate the expression using a stack
Token Exec(Stack<Token> operatorStack, Stack<Token> operandStack)
{
var op = operatorStack.Pop();
var t1 = operandStack.Pop();
var t2 = operandStack.Pop();
switch (op.Value)
{
case "+": return new Token() { Value = (int.Parse(t1.Value) + int.Parse(t2.Value)).ToString(), Type = TokenType.Operand };
case "-": return new Token() { Value = (int.Parse(t2.Value) - int.Parse(t1.Value)).ToString(), Type = TokenType.Operand };
case "*": return new Token() { Value = (int.Parse(t1.Value) * int.Parse(t2.Value)).ToString(), Type = TokenType.Operand };
case "/": return new Token() { Value = (int.Parse(t2.Value) / int.Parse(t1.Value)).ToString(), Type = TokenType.Operand };
}
return null;
}
int Eval(string input)
{
var tokens = Parse(input);
var operatorStack = new Stack<Token>();
var operandStack = new Stack<Token>();
var precedence = new Dictionary<string, int>() { { "+", 0 }, { "-", 0 }, { "*", 1 }, { "/", 1 } };
foreach (var token in tokens)
{
if (token.Type == TokenType.Operand) operandStack.Push(token);
if (token.Type == TokenType.Operator)
{
while (operatorStack.Count > 0 && precedence[operatorStack.Peek().Value] >= precedence[token.Value])
{
operandStack.Push(Exec(operatorStack, operandStack));
}
operatorStack.Push(token);
}
}
while(operatorStack.Count>0)
{
operandStack.Push(Exec(operatorStack, operandStack));
}
return int.Parse(operandStack.Pop().Value);
}
You can test your code now.
int r1 = Eval("25 - 5");
int r2 = Eval("25 - 5*2");
int r3 = Eval("25 - 5 + 3*2");
int r4 = Eval("25/5 + 7*3");
int r5 = Eval("25/5 + 7*3 + 2");
int r6 = Eval("25/5 + 7*3 * 2");

Format Text from a Textbox as a Percent

I have a numeric value in a Textbox that I'd like to format as a percent. How can I do this in C# or VB.NET?
In VB.NET...
YourTextbox.Text = temp.ToString("0%")
And C#...
YourTextbox.Text = temp.ToString("0%");
Building on Larsenal's answer, how about using the TextBox.Validating event something like this:
yourTextBox_Validating(object sender, CancelEventArgs e)
{
double doubleValue;
if(Double.TryParse(yourTextBox.Text, out doubleValue))
{
yourTextBox.Text = doubleValue.ToString("0%");
}
else
{
e.Cancel = true;
// do some sort of error reporting
}
}
For added fun, let's make the parser a bit more sophisticated.
Instead of Double.TryParse, let's create Percent.TryParse which passes these tests:
100.0 == " 100.0 "
55.0 == " 55% "
100.0 == "1"
1.0 == " 1 % "
0.9 == " 0.9 % "
90 == " 0.9 "
50.0 == "50 "
1.001 == " 1.001"
I think those rules look fair if I was a user required to enter a percent. It allows you to enter decimal values along with percents (requiring the "%" end char or that the value entered is greater than 1).
public static class Percent {
static string LOCAL_PERCENT = "%";
static Regex PARSE_RE = new Regex(#"([\d\.,]+)\s*("+LOCAL_PERCENT+")?");
public static bool TryParse(string str, out double ret) {
var m = PARSE_RE.Match(str);
if (m.Success) {
double val;
if (!double.TryParse(m.Groups[1].Value, out val)) {
ret = 0.0;
return false;
}
bool perc = (m.Groups[2].Value == LOCAL_PERCENT);
perc = perc || (!perc && val > 1.0);
ret = perc ? val : val * 100.0;
return true;
}
else {
ret = 0.0;
return false;
}
}
public static double Parse(string str) {
double ret;
if (!TryParse(str, out ret)) {
throw new FormatException("Cannot parse: " + str);
}
return ret;
}
public static double ParsePercent(this string str) {
return Parse(str);
}
}
Of course, this is all overkill if you simply put the "%" sign outside of the TextBox.
A little trickery for populating Label's (& TexBox) in a panel before users input. This covers decimal, integers, percent, and strings.
Using C# 1.1 in the Page_Load event before any thing happens:
if (!this.IsPostBack)
{
pnlIntake.Visible = true // what our guest will see & then disappear
pnlResult.Visible = false // what will show up when the 'Submit' button fires
txtIperson.Text = "enter who";
lbl1R.Text = String.Format(Convert.ToString(0)); // how many times
lbl2R.Text = String.Format(Convert.ToString(365)); // days a year
lblPercentTime = String.Format("{0:p}", 0.00); // or one zero will work '0'
lblDecimal = String.Format("{0:d}", 0.00); // to use as multiplier
lblMoney = String.Format("{0:c}", 0.00); // I just like money
// < some code goes here - if you want
}

Categories

Resources