capcom
capcom

Reputation: 3337

Android: Parse simple mathematical formula from string

I have users entering numbers into an EditText fields, but what I would like them to be able to enter is 100+32+10 into the fields as well. I expect simple expressions only, common four functions. In fact, just addition would cut it too.

For just addition, I guess it wouldn't be that hard to split up the string and do it myself I suppose, but I'm curious to know if there is a library which can do what I want much more cleanly.

Any suggestions?

Upvotes: 1

Views: 6453

Answers (2)

capcom
capcom

Reputation: 3337

Just to let everyone know, I solved my problem by writing these few lines of code:

public float calculateBillAmount(String expression){

    String delim = "\\+";
    String[] stringTokens = expression.split(delim);
    float result = 0;

    for (int i = 0; i < stringTokens.length; i++)   {
        result += Float.parseFloat(stringTokens[i]);
    }

    return result;
}

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160191

There are a ton of Java expression libraries.

I've used JEXL on Android with no issues, but there are plenty of other options.

A full-on EL might be more than you need; essentially everybody in the world has written simple expression parsers that might be adequate for your needs, or roll a quick one yourself.

Upvotes: 2

Related Questions