Dart: Make a calculation from a user input String including math operators

3,155

Solution 1

If you are looking for simple mathematical strings, you calculate them with the help of a package called

First install this package. Add it into your project and then implement this code.

import 'dart:math';
import 'package:petitparser/petitparser.dart';

Parser buildParser() {
  final builder = ExpressionBuilder();
  builder.group()
    ..primitive((pattern('+-').optional() &
            digit().plus() &
            (char('.') & digit().plus()).optional() &
            (pattern('eE') & pattern('+-').optional() & digit().plus())
                .optional())
        .flatten('number expected')
        .trim()
        .map(num.tryParse))
    ..wrapper(
        char('(').trim(), char(')').trim(), (left, value, right) => value);
  builder.group()..prefix(char('-').trim(), (op, a) => -a);
  builder.group()..right(char('^').trim(), (a, op, b) => pow(a, b));
  builder.group()
    ..left(char('*').trim(), (a, op, b) => a * b)
    ..left(char('/').trim(), (a, op, b) => a / b);
  builder.group()
    ..left(char('+').trim(), (a, op, b) => a + b)
    ..left(char('-').trim(), (a, op, b) => a - b);
  return builder.build().end();
}

double calcString(String text) {
  final parser = buildParser();
  final input = text;
  final result = parser.parse(input);
  if (result.isSuccess)
    return result.value.toDouble();
  else
    return double.parse(text);
}

Now just call this function calcString and you will get the required answer. Remember it will only return the calculated value if the given string is valid else it will throw an error.

Solution 2

I think what you are looking for is a package that can do "expression evaluation". Searching on the pub site for "expression" yields a few results that look promising.

I don't have any direct experience with these packages so I can't recommend one.

Share:
3,155
Aembe
Author by

Aembe

Updated on December 09, 2022

Comments

  • Aembe
    Aembe over 1 year

    i am new in Dart and Flutter. Is there an easy way to calculate an user input as a String like '3+5/8? Of course the result should be double-type. Thanks for your answers!