EvalStr

Method

Parses and evaluates an expression in a single step, returning the result of any data type as a string with optional formatting selection

Product: 

Class: 

Warning

uCalc API Preview Release Notice:The uCalc engine has successfully transitioned to modern cross-platform environments.The next phase envolves some structural changes, performance optimizations, and API refinements.The API is subject to breaking changes prior to the stable release. Please evaluate the preview version thoroughly before production use.

Syntax

EvalStr(string, FormatStyle, int32)

Parameters

expression
string
The string containing the mathematical or logical expression to parse and evaluate.
formatStyle
FormatStyle
(Default = FormatStyle::Default)
The formatting style to apply to numeric results (e.g., General, Scientific, Fixed, Hex).
precision
int32
(Default = -1)
The number of digits of precision to include for numeric results. If omitted or set to `-1`, default precision is used.

Return

string

A string containing the formatted or raw result of the evaluation, or an error message if the expression is invalid.

Remarks

Syntax (Overload - Custom Format String): EvalStr(string expression, string formatString)

Parameters (Overload):

  • expression - string - The string containing the mathematical or logical expression to parse and evaluate.
  • formatString - string - A formatting expression in the form of "Result = [expression]" that manipulates the evaluated output before returning it.

The EvalStr method is a versatile, one-step function that parses and evaluates an expression, returning the result as a string. It is the most convenient way to get a display-ready result from user input, as it handles any data type and can automatically apply custom formatting. This method is a high-level convenience wrapper around the two-step process of using uCalc.Parse followed by Expression.EvaluateStr.

💡 Key Features

  • Universal Type Support: Unlike its counterpart uCalc.Eval, which is optimized for and returns a double, EvalStr works with any data type defined in uCalc, including String, Complex, Boolean, and user-defined types.
  • Safe Error Handling: If a syntax or evaluation error occurs (like a typo or division by zero), EvalStr does not throw an exception. Instead, it safely returns the error message as a string, making it ideal for processing raw user input without needing complex try-catch blocks.
  • Automatic Formatting: The result can be automatically passed through any defined output formatters, controlled by the format or formatStyle parameter.

Eval vs. EvalStr

FeatureEval(string)EvalStr(string)
Return Typedoublestring
Supported TypesNumeric types (or types convertible to double)All data types
Use CaseNumeric calculationsGeneral-purpose evaluation, user-facing output, non-numeric results
Error HandlingReturns NaN or Infinity; inspect with Error.CodeReturns the error message as a string

🎨 Output Formatting

EvalStr provides two primary approaches for controlling how the evaluated result is formatted:

  1. FormatStyle Enum & Precision:For quick, standardized numeric formatting, you can pass a FormatStyle enum (such as FormatStyle.Scientific, FormatStyle.Fixed, or FormatStyle.Hex) along with an optional precision integer.

    • If you pass only an expression with no additional arguments, FormatStyle.Default is used. This automatically applies any global user-defined formatting established via uCalc.Format().
    • If no global uCalc.Format() rules exist, numeric results fall back to FormatStyle.General with 15 digits of precision.
    • Passing FormatStyle.None bypasses any global uCalc.Format() rules and returns the raw value.
  2. Custom Format Expressions:For granular control over a specific call, you can pass a custom format expression as the second parameter. This string takes the form of "Result = [expression with Result]", where Result is a temporary variable holding the string representation of the evaluated output.

    • You can use simple string concatenation (e.g., "Result = 'Output: ' + Result") or leverage the built-in Format() function for advanced alignment and interpolation.
    • Because Result holds the output in string form, numeric values should be converted (e.g., double(Result)) when passed into numeric formatting specifiers.
    • Pattern Reference: The Format() function uses standard C++ / Python-style format specifiers (e.g., {:6} for width, {:.2f} for fixed-point, {:#x} for hex). For a complete guide on available formatting patterns, refer to the Format String Syntax Guide or the C++ Standard Format Specification.

Comparative Analysis

vs. eval() in Scripting Languages (JavaScript, Python)While functionally similar, uCalc's EvalStr is vastly more secure. Scripting language eval() functions can often execute arbitrary code, creating significant security vulnerabilities (code injection). EvalStr operates within a sandboxed environment defined by your uCalc instance; it can only execute the functions, operators, and variables you have explicitly defined and cannot interact with the host system's file system, network, or other resources without being given explicit access.

vs. Manual Parsing in C++/C#Implementing a robust expression evaluator from scratch is a complex task involving tokenization, abstract syntax tree (AST) construction, type checking, and evaluation logic. EvalStr abstracts all this complexity into a single, powerful function call, dramatically reducing development time and potential for bugs.

Examples

Demonstrates basic, one-line evaluations for numeric, string, and boolean expressions.

ID: 337

See: EvalStr
				
					using uCalcSoftware;

var uc = new uCalc();
// Basic arithmetic
Console.WriteLine(uc.EvalStr("15 * (4 + 3)"));
// String manipulation
Console.WriteLine(uc.EvalStr("UCase('hello') + ', world!'"));
// Boolean logic
Console.WriteLine(uc.EvalStr("10 > 5 AndAlso 'a' < 'b'"));
				
			
105
HELLO, world!
true
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // Basic arithmetic
   cout << uc.EvalStr("15 * (4 + 3)") << endl;
   // String manipulation
   cout << uc.EvalStr("UCase('hello') + ', world!'") << endl;
   // Boolean logic
   cout << uc.EvalStr("10 > 5 AndAlso 'a' < 'b'") << endl;
}
				
			
105
HELLO, world!
true
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// Basic arithmetic
      Console.WriteLine(uc.EvalStr("15 * (4 + 3)"))
      '// String manipulation
      Console.WriteLine(uc.EvalStr("UCase('hello') + ', world!'"))
      '// Boolean logic
      Console.WriteLine(uc.EvalStr("10 > 5 AndAlso 'a' < 'b'"))
   End Sub
End Module
				
			
105
HELLO, world!
true
Calculates a total price using predefined variables and demonstrates the effect of output formatting.

ID: 338

See: EvalStr
				
					using uCalcSoftware;

var uc = new uCalc();
// Define some context for the expression
uc.DefineVariable("price = 49.99");
uc.DefineVariable("quantity = 3");
uc.DefineConstant("TAX_RATE = 0.0825");

// Define a format for currency output
uc.Format("DataType: Double, Def: result = '$' + result");

// Expression to calculate total price, using variables
var expression = "price * quantity * (1 + TAX_RATE)";

// Evaluate with formatting enabled
Console.WriteLine($"Formatted Total: {uc.EvalStr(expression, FormatStyle.Default)}");

// Evaluate with formatting disabled
Console.WriteLine($"Raw Total: {uc.EvalStr(expression, FormatStyle.None)}");
				
			
Formatted Total: $162.342525
Raw Total: 162.342525
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // Define some context for the expression
   uc.DefineVariable("price = 49.99");
   uc.DefineVariable("quantity = 3");
   uc.DefineConstant("TAX_RATE = 0.0825");

   // Define a format for currency output
   uc.Format("DataType: Double, Def: result = '$' + result");

   // Expression to calculate total price, using variables
   auto expression = "price * quantity * (1 + TAX_RATE)";

   // Evaluate with formatting enabled
   cout << "Formatted Total: " << uc.EvalStr(expression, FormatStyle::Default) << endl;

   // Evaluate with formatting disabled
   cout << "Raw Total: " << uc.EvalStr(expression, FormatStyle::None) << endl;
}
				
			
Formatted Total: $162.342525
Raw Total: 162.342525
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// Define some context for the expression
      uc.DefineVariable("price = 49.99")
      uc.DefineVariable("quantity = 3")
      uc.DefineConstant("TAX_RATE = 0.0825")
      
      '// Define a format for currency output
      uc.Format("DataType: Double, Def: result = '$' + result")
      
      '// Expression to calculate total price, using variables
      Dim expression = "price * quantity * (1 + TAX_RATE)"
      
      '// Evaluate with formatting enabled
      Console.WriteLine($"Formatted Total: {uc.EvalStr(expression, FormatStyle.Default)}")
      
      '// Evaluate with formatting disabled
      Console.WriteLine($"Raw Total: {uc.EvalStr(expression, FormatStyle.None)}")
   End Sub
End Module
				
			
Formatted Total: $162.342525
Raw Total: 162.342525
Evaluating expressions returned as string

ID: 23

See: EvalStr
				
					using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("x = 123");
uc.DefineVariable("y");

Console.WriteLine(uc.EvalStr("1 + 1"));
Console.WriteLine(uc.EvalStr("UCase('Hello ' + 'world!')"));
Console.WriteLine(uc.EvalStr("$'Interpolation: {2+3}'"));
Console.WriteLine(uc.EvalStr("#b101 + #hAE"));
Console.WriteLine(uc.EvalStr("Hex(1234)"));
Console.WriteLine(uc.EvalStr("(3+5*#i)^2"));
Console.WriteLine(uc.EvalStr("3 > 4"));
Console.WriteLine(uc.EvalStr("Max(5, 10, 3, -5)"));
Console.WriteLine(uc.EvalStr("x * 10"));
uc.EvalStr("x = 456");
Console.WriteLine(uc.EvalStr("x"));
Console.WriteLine(uc.EvalStr("2+4, 5+4, 10+20"));
Console.WriteLine(uc.EvalStr("y=100; ForLoop(x, 1, 10, 1, y = y + x); y"));
Console.WriteLine(uc.EvalStr("10 / "));
				
			
2
HELLO WORLD!
Interpolation: 5
179
4d2
-16+30i
false
10
1230
456
30
155
Syntax error
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   uc.DefineVariable("x = 123");
   uc.DefineVariable("y");

   cout << uc.EvalStr("1 + 1") << endl;
   cout << uc.EvalStr("UCase('Hello ' + 'world!')") << endl;
   cout << uc.EvalStr("$'Interpolation: {2+3}'") << endl;
   cout << uc.EvalStr("#b101 + #hAE") << endl;
   cout << uc.EvalStr("Hex(1234)") << endl;
   cout << uc.EvalStr("(3+5*#i)^2") << endl;
   cout << uc.EvalStr("3 > 4") << endl;
   cout << uc.EvalStr("Max(5, 10, 3, -5)") << endl;
   cout << uc.EvalStr("x * 10") << endl;
   uc.EvalStr("x = 456");
   cout << uc.EvalStr("x") << endl;
   cout << uc.EvalStr("2+4, 5+4, 10+20") << endl;
   cout << uc.EvalStr("y=100; ForLoop(x, 1, 10, 1, y = y + x); y") << endl;
   cout << uc.EvalStr("10 / ") << endl;
}
				
			
2
HELLO WORLD!
Interpolation: 5
179
4d2
-16+30i
false
10
1230
456
30
155
Syntax error
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      uc.DefineVariable("x = 123")
      uc.DefineVariable("y")
      
      Console.WriteLine(uc.EvalStr("1 + 1"))
      Console.WriteLine(uc.EvalStr("UCase('Hello ' + 'world!')"))
      Console.WriteLine(uc.EvalStr("$'Interpolation: {2+3}'"))
      Console.WriteLine(uc.EvalStr("#b101 + #hAE"))
      Console.WriteLine(uc.EvalStr("Hex(1234)"))
      Console.WriteLine(uc.EvalStr("(3+5*#i)^2"))
      Console.WriteLine(uc.EvalStr("3 > 4"))
      Console.WriteLine(uc.EvalStr("Max(5, 10, 3, -5)"))
      Console.WriteLine(uc.EvalStr("x * 10"))
      uc.EvalStr("x = 456")
      Console.WriteLine(uc.EvalStr("x"))
      Console.WriteLine(uc.EvalStr("2+4, 5+4, 10+20"))
      Console.WriteLine(uc.EvalStr("y=100; ForLoop(x, 1, 10, 1, y = y + x); y"))
      Console.WriteLine(uc.EvalStr("10 / "))
   End Sub
End Module
				
			
2
HELLO WORLD!
Interpolation: 5
179
4d2
-16+30i
false
10
1230
456
30
155
Syntax error
How to perform a summation in a loop efficiently using Execute() instead of Evaluate().

ID: 22

				
					using uCalcSoftware;

var uc = new uCalc();
var VariableX = uc.DefineVariable("x = 0");
var Total = uc.DefineVariable("Total");
string Expression = "x++; Total = Total + x^2 + 5";

var ParsedExpr = uc.Parse(Expression);

for (double x = 1; x <= 10; x++) {
   // Execute() runs the parsed expression without the overhead of returning a value.
   // This provides near-native performance for loops across C#, VB, and C++.
   ParsedExpr.Execute();

   // Evaluate string interpolation to output the final calculated total
   Console.WriteLine(uc.EvalStr("$'{x}   Sub total = {Total}'"));
}

Console.WriteLine(uc.EvalStr("$'Total = {Total}'"));

ParsedExpr.Release();
VariableX.Release();
				
			
1   Sub total = 6
2   Sub total = 15
3   Sub total = 29
4   Sub total = 50
5   Sub total = 80
6   Sub total = 121
7   Sub total = 175
8   Sub total = 244
9   Sub total = 330
10   Sub total = 435
Total = 435
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   auto VariableX = uc.DefineVariable("x = 0");
   auto Total = uc.DefineVariable("Total");
   string Expression = "x++; Total = Total + x^2 + 5";

   auto ParsedExpr = uc.Parse(Expression);

   for (double x = 1; x <= 10; x++) {
      // Execute() runs the parsed expression without the overhead of returning a value.
      // This provides near-native performance for loops across C#, VB, and C++.
      ParsedExpr.Execute();

      // Evaluate string interpolation to output the final calculated total
      cout << uc.EvalStr("$'{x}   Sub total = {Total}'") << endl;
   }

   cout << uc.EvalStr("$'Total = {Total}'") << endl;

   ParsedExpr.Release();
   VariableX.Release();
}
				
			
1   Sub total = 6
2   Sub total = 15
3   Sub total = 29
4   Sub total = 50
5   Sub total = 80
6   Sub total = 121
7   Sub total = 175
8   Sub total = 244
9   Sub total = 330
10   Sub total = 435
Total = 435
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim VariableX = uc.DefineVariable("x = 0")
      Dim Total = uc.DefineVariable("Total")
      Dim Expression As String = "x++; Total = Total + x^2 + 5"
      
      Dim ParsedExpr = uc.Parse(Expression)
      
      For x  As Double = 1 To 10
         '// Execute() runs the parsed expression without the overhead of returning a value.
         '// This provides near-native performance for loops across C#, VB, and C++.
         ParsedExpr.Execute()
         
         '// Evaluate string interpolation to output the final calculated total
         Console.WriteLine(uc.EvalStr("$'{x}   Sub total = {Total}'"))
      Next
      
      Console.WriteLine(uc.EvalStr("$'Total = {Total}'"))
      
      ParsedExpr.Release()
      VariableX.Release()
   End Sub
End Module
				
			
1   Sub total = 6
2   Sub total = 15
3   Sub total = 29
4   Sub total = 50
5   Sub total = 80
6   Sub total = 121
7   Sub total = 175
8   Sub total = 244
9   Sub total = 330
10   Sub total = 435
Total = 435
Using custom format strings to format double and string outputs

ID: 1471

See: EvalStr
				
					using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("num = 42");
uc.DefineVariable("txt = 'Hello'");

// Using modern format strings with alignment and casting
Console.WriteLine(uc.EvalStr("num", "Result = Format('--{:6}--', double(Result))"));

// Using multiple placeholder references
Console.WriteLine(uc.EvalStr("txt", "Result = Format('{0}! and {0}', Result)"));
				
			
--    42--
Hello! and Hello
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   uc.DefineVariable("num = 42");
   uc.DefineVariable("txt = 'Hello'");

   // Using modern format strings with alignment and casting
   cout << uc.EvalStr("num", "Result = Format('--{:6}--', double(Result))") << endl;

   // Using multiple placeholder references
   cout << uc.EvalStr("txt", "Result = Format('{0}! and {0}', Result)") << endl;
}
				
			
--    42--
Hello! and Hello
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      uc.DefineVariable("num = 42")
      uc.DefineVariable("txt = 'Hello'")
      
      '// Using modern format strings with alignment and casting
      Console.WriteLine(uc.EvalStr("num", "Result = Format('--{:6}--', double(Result))"))
      
      '// Using multiple placeholder references
      Console.WriteLine(uc.EvalStr("txt", "Result = Format('{0}! and {0}', Result)"))
   End Sub
End Module
				
			
--    42--
Hello! and Hello
Formatting a calculated result using the FormatStyle Enum

ID: 1472

See: EvalStr
				
					using uCalcSoftware;

var uc = new uCalc();
// Evaluate an expression and format it as Scientific notation with 4 digits of precision
var result = uc.EvalStr("10000 / 3", FormatStyle.Scientific, 4);
Console.WriteLine(result);
				
			
3.3333e+03
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // Evaluate an expression and format it as Scientific notation with 4 digits of precision
   auto result = uc.EvalStr("10000 / 3", FormatStyle::Scientific, 4);
   cout << result << endl;
}
				
			
3.3333e+03
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// Evaluate an expression and format it as Scientific notation with 4 digits of precision
      Dim result = uc.EvalStr("10000 / 3", FormatStyle.Scientific, 4)
      Console.WriteLine(result)
   End Sub
End Module
				
			
3.3333e+03

This page last modified on: 

10/15/2026