how to Convert String To Float in C# [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Hello guy i am creating calculator and i want to convert these values to float
string num = "2+6+8+9";
so they will automatically add and give total of 25?
is there anyway to do this?
sorry for my bad english

Use DataTable.Compute ;-)
DataTable table = new DataTable();
int i = (int) table.Compute("2+6+8+9", null); // 25
For all rules and which operators are supported: DataColumn.Expression
If you don't know the type of the result use a floating point type always and System.Convert.ToDouble which accepts everything that's IConvertible, for example:
double d1 = System.Convert.ToDouble(table.Compute("2+6+8+9", null)); // 25.0
double d2 = System.Convert.ToDouble(table.Compute("2+6+8+9/2", null)); // 20.5

You are looking for an expression evaluator. There are many available. For example: http://csharpeval.codeplex.com/

The question asked in your subject is straight forward. You can convert a string to a float like this:
double f = double.Parse("2.5");
However, if you want to handle arbitrary expressions as described in your question, that requires a bit more work. Fortunately, others have done this work. I wrote my own expression evaluator and you can see it in my article A C# Expression Evaluator. It supports variables and functions in addition to supporting the sample expression in your question.

This may get you what you want:
string[] inputArray = Regex.Split(num, #"\D+");
float results = 0;
foreach (var item in inputArray )
{
results += float.Parse(item);
}

Related

using a function inside a lamba expression [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
To manage rounding there are usually two methods, the first method is round values then to sum them. Or sum values then to round them. Of course to the required precision that you want.
I want to go with the first method and I need to update this line that currently do the opposite.
this.ClonedEntity.MontantHT = ArroundDecimal.CustomDecimalArround(correctedLines.Sum(l => l.MontantHT ?? 0));
When I try to call my static method in the lambda expression it doesn't work.
How would you suggest to do it while keeping use of the linq syntax ?
Thank you.
You could try something like this:
this.ClonedEntity.MontantHT = correctedLines
.Select(x=>ArroundDecimal.CustomDecimalArround(x.MontantHT ?? 0))
.Sum();
something = correctedLines.Sum(l => ArroundDecimal.CustomDecimalArround(l.MontantHT ?? 0))

Writing a recursive function in C# to create a string from characters [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
Currently, I have something like the following:
public char functName(int n)
{
some functionality....
if(condition1)
return convertFuncToChar(variable) + functName(modifiedNumber);
else
return convertFuncToChar(variable);
}
however, I realize that doesn't give me a string (and the syntax shows that there's an error).
I know that for c++, I would most likely use char* to initialize the function, but this is C#.
I don't think it works if I initialize with String either.
Assuming I understand the question correctly, you can take advantage of two things:
1) all basic types implement .ToString(), which creates a string for you
2) string implements operator+()
The following is an example of a recursive function that will recursively concatenate characters to create a string. The output is the number in reverse as a string.
static string funcName(int n)
{
if (n<10)
return (n%10).ToString();
return (n%10).ToString() + funcName(n/10);
}
Of course, it would be more efficient to write this non-recursively.

C# Converting string to int fails [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I am working on a little project, that at a certain point need to convert a string to int.
I tried the following things:
//first try
value1 = int.TryParse(value[0].tostring(), out i)
//second
value1 = Convert.ToInt32(value[0].tostring())
//third
value1 = int.Parse(value[0].tostring())
I even wrote my own conversion method because I was at a loss.
The values I am trying to convert are queried from a MySQL database.
Thank for your help
EDIT:
I know tryparse should have 2 params.
And the error iam getting is a formatexception
Input string was not in a correct format.
I got that on all the tries.
the value in my test case is 2500
Keep in mind that that number is received from a db
I tried the above snippets while using a hard coded value. And that works fine.
EDIT 2:
//http://imgur.com/NSyg2rJ
One:
The signature of int.TryParse() is incorrect:
int result = 0;
bool parsedSuccessfully = Int32.TryParse(value[0].ToString(), out result);
//If successful, result will hold the value.
Two:
The signature of Convert.ToInt32() is correct, minus the case of the .ToString() method. This is failing because value or value[0] is null, or it cannot convert something like the string "NotAnInt" to an int.
Three:
The signature of int.Parse() is correct, but is failing for the same reasons as two.
Try this -
int value1;
if (Int.TryParse(value[0].ToString(), out value1))
{
//conversion successful
}

c# Regular Expression for the text below? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have strings of array.
One of the strings:
myText = "[Date].[Hierarchy].[Year].&[2005].&[Q1].&[Jan]"
The [Date].[Hierarchy].[Year].& part is always the same, but the rest is changing depending on the today date.
So it would be for today like [Date].[Hierarchy].[Year].&[2013].&[Q3].&[Jul], but in the array I also have other strings that like [Date].[Hierarchy].[Year].&[2005].&[Q1].&[Jan].&[20].
The regex should opt those out also.
I am only interested in strings from array like [Date].[Hierarchy].[Year].&[2005].&[Q1].&[Jan]", [Date].[Hierarchy].[Year].&[2005].&[Q1].&[Feb], [Date].[Hierarchy].[Year].&[2005].&[Q1].&[Mar], ....
I hope you get the pattern.
This Regex should do it. The year is currently set to 4 digits, if you only want it to match 2005, replace the \d{4} bit.
^\[Date\]\.\[Hierarchy\]\.\[Year\]\.&\[\d{4}\]\.&\[Q1\]\.&\[[A-Z-a-z]{3}\]$
Here's the result:
[Date].[Hierarchy].[Year].&[2005].&[Q1].&[Jan] // matches
[Date].[Hierarchy].[Year].&[2013].&[Q3].&[Jul] // no match
[Date].[Hierarchy].[Year].&[2005].&[Q1].&[Jan].&[20] // no match
Edit to your comment: Make sure you put an # before the string declaration.
var pattern = new Regex(#"^\[Date\]\.\[Hierarchy\]\.\[Year\]\.&\[\d{4}\]\.&\[Q1\]\.&\[[A-Z-a-z]{3}\]$");
var matches = pattern.IsMatch("[Date].[Hierarchy].[Year].&[2005].&[Q1].&[Jan]");

How to convert string formula to a mathematical formula in C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
If I have a string variable with a formula:
string myformula = "3 * 5 + Pow(2,3)";
How can I convert this string to a mathematical formula that the compiler can calculate?
Finally I got the FLEE library for this purpose. The tool is free and perfectly fit for your purpose.
Below is an example how to use this library:
// Define the context of our expression
ExpressionContext context = new ExpressionContext();
// Allow the expression to use all static public methods of System.Math
context.Imports.AddType(typeof(Math));
// Define an int variable
context.Variables["a"] = 100;
// Create a dynamic expression that evaluates to an Object
IDynamicExpression eDynamic = context.CompileDynamic("sqrt(a) + pi");
// Evaluate the expressions
double result = (double)eDynamic.Evaluate();
Not sure why would you mention a compiler, but the simplest way will be to use a math expression evaluator, for example NCalc.
You could add a reference to Microsoft Script Control Library (COM) and use code like this to evaluate an expression. (Also works for JScript.)
MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();
sc.Language = "VBScript";
string expression = "1 + 2 * 7";
object result = sc.Eval(expression);
MessageBox.Show(result.ToString());

Categories

Resources