info.bliki.wiki.template.Expr Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of bliki-core Show documentation
Show all versions of bliki-core Show documentation
This is the core project.
The newest version!
package info.bliki.wiki.template;
import info.bliki.wiki.filter.TemplateParser;
import info.bliki.wiki.model.Configuration;
import info.bliki.wiki.model.IWikiModel;
import info.bliki.wiki.template.expr.eval.DoubleEvaluator;
import java.io.IOException;
import java.util.List;
/**
* A template parser function for {{ #expr: ... }}
syntax.
*
* See
* Mediwiki's Help:Extension:ParserFunctions See: Expr.php in MediaWiki SVN orWikipedia -
* Help:Calculation.
*/
public class Expr extends AbstractTemplateFunction {
public final static ITemplateFunction CONST = new Expr();
@Override
public String parseFunction(List list, IWikiModel model, char[] src, int beginIndex, int endIndex, boolean isSubst)
throws IOException {
if (list.size() > 0) {
String expression = parseTrim(list.get(0), model);
if (expression.length() == 0) {
return null;
}
if (!isSubst) {
StringBuilder conditionBuffer = new StringBuilder(expression.length());
TemplateParser.parse(expression, model, conditionBuffer, false);
if (conditionBuffer.length() == 0) {
return null;
}
expression = conditionBuffer.toString();
}
try {
DoubleEvaluator engine = new DoubleEvaluator();
double d = engine.evaluate(expression);
return getWikiNumberFormat(d,model);
} catch (Exception e) {
if (Configuration.DEBUG) {
System.out.println("#expr error: "+expression);
}
if (Configuration.STACKTRACE) {
e.printStackTrace();
}
return "Expression error: " + e.getMessage() + "";
// e.printStackTrace();
}
}
return null;
}
public static String getWikiNumberFormat(double d,IWikiModel model) {
double dInt = Math.rint(d);
// if (dInt == d) {
if (Math.abs(dInt - d) < DoubleEvaluator.EPSILON) {
return Long.toString(Math.round(d));
}
return Double.toString(d).toUpperCase();
}
}