Skip to content

Instantly share code, notes, and snippets.

@ggtools
Created February 1, 2013 07:13
Show Gist options
  • Save ggtools/4689866 to your computer and use it in GitHub Desktop.
Save ggtools/4689866 to your computer and use it in GitHub Desktop.
CodeStory 2013: Calculateur
public String solve(HttpServletRequest request) throws ResolverException {
String q = request.getParameter("q");
if (q == null) return null;
String expr = q.replace(',', '.').replaceAll(" ", "+");
try {
GroovyShell shell = new GroovyShell();
Object evalResult = shell.evaluate(expr);
Object result;
if (evalResult instanceof BigDecimal) {
BigDecimal bigDecimal = (BigDecimal) evalResult;
result = bigDecimal.stripTrailingZeros();
} else {
result = evalResult;
}
return result.toString().replace('.', ',');
} catch (Exception e) {
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment