Evaluator.java

package org.microspace.evaluator;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

/**
 * @author Gaspar Sinai - {@literal gaspar.sinai@microspace.org}
 * @version 2017-10-16
 */
public class Evaluator implements Serializable {
	private static final long serialVersionUID = -827277398273190218L;
	final public Expression expression;
	
	public Evaluator(Expression expression) {
		this.expression = expression;
	}
	public static final int DEFAULT_SCALE = 20;
	public static final int DEFAULT_PRECISION = 6;
	
	private int scale = DEFAULT_SCALE;
	private int precision = DEFAULT_PRECISION;
	
	public void setVariable(String variable, BigDecimal value) {
		expression.setVariable(variable, value, null);
	}
	
	public void setVariable(String variable, BigDecimal value, String alias) {
		expression.setVariable(variable, value, alias);
	}
	
	public void clear() {
		expression.clear();
		scale = DEFAULT_SCALE;
		precision = DEFAULT_PRECISION;
	}
	
	public int getScale() {
		return scale;
	}

	public int getPrecision() {
		return precision;
	}

	public void setScale (int scale) {
		this.scale = scale;
	}
	
	public void setPrecision (int precision) {
		this.precision = precision;
	}
	
	public BigDecimal calculate() {
		BigDecimal value = expression.calculate (scale);
		BigDecimal ret = value.round(new MathContext(precision, RoundingMode.HALF_UP));
		return ret;
	}
	public String format(EvaluatorFormat format) {
		return expression.format(format, scale, precision);
		
	}

}