-1

I'm making a calculator. It will be very long and hard to do the proper string analizer which parses strings by chars, so I thought, is there a way to turn string into a command line like this:

double num = "12/6+23*4";
Lekret
  • 11
  • 1
  • 3
  • You can dynamically compile a C# dll which will allow anyone to run malicious code. Don't ever eval anything unless you know whaat you are doing. Instead, split the string into "tokens", single numbers, symbols, operators. Use a list of tokens to create operations and then sort them. – Peri Sep 04 '20 at 11:09
  • It's hard to guage the scope and context of your task based on the terse example you have given. Consider wrting more about where you intend to use the calculater. Is it homework for a class, will it be parsing a string passed from the arguments of the CLI. More details are necessary for good answers. – mhvelplund Sep 04 '20 at 12:24

1 Answers1

0

There is a small and simple trick to do this. First, import the namespace

using System.Data;

and after that,

string math = "12.0/6+23*4";
decimal value = (decimal)new DataTable().Compute(math, null);
//value = 94.0
Roman Ryzhiy
  • 1,540
  • 8
  • 5