commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From henrib <hen...@apache.org>
Subject Re: [jexl]
Date Tue, 10 Apr 2012 08:10:57 GMT
Howdy;
I suppose you are expecting the result to be a BigDecimal ?
Something like:

    public void test131() throws Exception {
        BigDecimal sevendot475 = new BigDecimal("7.475");
        BigDecimal SO = new BigDecimal("325");
        JexlContext jc = new MapContext();
        jc.set("SO", SO);

        JexlEngine jexl = new Engine();
        String expr = "2.3*SO/100";

        Object evaluate = jexl.createExpression(expr).evaluate(jc);
        assertEquals(sevendot475, (BigDecimal) evaluate);
    }

If so, the JexlArithmetic can be specialized/derived (or patched) to get
this result by overriding (changing) the code in
JexlArithmetic.{add,subtract,multiply,divide,mod} to check first for
BigDecimal rather than floating point numbers as in:

    public Object add(Object left, Object right) {
        if (left == null && right == null) {
            return controlNullNullOperands();
        }
        try {
            // if either are bigdecimal use that type
            if (left instanceof BigDecimal || right instanceof BigDecimal) {
                BigDecimal l = toBigDecimal(left);
                BigDecimal r = toBigDecimal(right);
                BigDecimal result = l.add(r, getMathContext());
                return narrowBigDecimal(left, right, result);
            }
            // if either are floating point (double or float) use double
            if (isFloatingPointNumber(left) || isFloatingPointNumber(right))
{
                double l = toDouble(left);
                double r = toDouble(right);
                return new Double(l + r);
            }
            // otherwise treat as integers
            BigInteger l = toBigInteger(left);
            BigInteger r = toBigInteger(right);
            BigInteger result = l.add(r);
            return narrowBigInteger(left, right, result);
        } catch (java.lang.NumberFormatException nfe) {
            // Well, use strings!
            if (left == null || right == null) {
                controlNullOperand();
            }
            return toString(left).concat(toString(right));
        }
    }

Hope this helps,
Cheers
Henrib


--
View this message in context: http://apache-commons.680414.n4.nabble.com/jexl-tp4542792p4544885.html
Sent from the Commons - User mailing list archive at Nabble.com.

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@commons.apache.org
For additional commands, e-mail: user-help@commons.apache.org


Mime
View raw message