ExpressionAtom.java
package org.microspace.evaluator;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* A literal expression.
*
* @author Gaspar Sinai - {@literal gaspar.sinai@microspace.org}
* @version 2017-10-16
*/
public class ExpressionAtom implements Expression {
private static final long serialVersionUID = -2804310178262424680L;
public enum Operator {
TIMES("*"),
SLASH("/"),
PLUS("+"),
MINUS("-");
String stringValue;
Operator(String stringValue) {
this.stringValue= stringValue;
}
public String getStringValue() {
return stringValue;
}
}
final Expression operand1;
final Operator operator;
final Expression operand2;
boolean needsBracket;
public ExpressionAtom (Expression operand1, Operator operator, Expression operand2) {
this.operand1 = operand1;
this.operator = operator;
this.operand2 = operand2;
}
@Override
public void setVariable(String variable, BigDecimal value, String alias) {
operand1.setVariable(variable, value, alias);
operand2.setVariable(variable, value, alias);
}
@Override
public void clear () {
operand1.clear();
operand2.clear();
}
@Override
public BigDecimal calculate(int scale) {
BigDecimal value1 = operand1.calculate(scale);
BigDecimal value2 = operand2.calculate(scale);
switch (operator) {
case MINUS:
return value1.subtract(value2);
case PLUS:
return value1.add(value2);
case SLASH:
return value1.divide(value2, scale, RoundingMode.HALF_UP);
case TIMES:
return value1.multiply(value2);
default:
return null;
}
}
@Override
public String format(EvaluatorFormat format, int scale, int accuracy) {
String value1 = operand1.format(format, scale, accuracy);
String value2 = operand2.format(format, scale, accuracy);
String lparen = needsBracket ? "( " : "";
String rparen = needsBracket ? " )" : "";
return lparen + value1 + " " + operator.getStringValue() + " " + value2 + rparen;
}
@Override
public void setNeedsBracket(boolean needsBracket) {
this.needsBracket = needsBracket;
}
}