I have some JavaScript which evaluates user defined expressions on the
file. These expressions are simple mathematical operations such as
add, subtract, multiply and divide and due to precision I require the
use of BigDecimal. However, when I attempt to call the appropriate
method to perform the mathematical operation between two BigDecimal
values within the JavaScript it tells me that it is looking for a
function. For example,
JavaScript:
var result = SourceAmount.multiply(Rate);
This tells me there is no function 'multiply' defined. The
'SourceAmount' and 'Rate' are passed as BigDecimal objects in the
script engines context.
Any help will greatly be appreciated
I think what may be happening here is that BigDecimal is not supported
by Rhino directly. If I'm correct, Rhino handles only
java.lang.Integer and java.lang.Double as primitives, and not the
generic java.lang.Number, of which BigDecimal is a subclass.
One way to solve this is to create your own BigDecimal class which
extends ScriptableObject/implements Scriptable, and using it as a
wrapper for java.lang.BigDecimal. There may be a neater way than this
- I'll leave that for anyone that knows better.
That's correct.
>
> One way to solve this is to create your own BigDecimal class which
> extends ScriptableObject/implements Scriptable, and using it as a
> wrapper for java.lang.BigDecimal. There may be a neater way than this
> - I'll leave that for anyone that knows better.
Since he's calling "multiply" directly, perhaps his needs are less
complex. At any rate, this works in Rhino as you'd expect:
js> var SourceAmount = new java.math.BigDecimal("32.2")
js> var Rate = new java.math.BigDecimal("12.1")
js> SourceAmount.multiply(Rate)
389.62
I think the symptoms indicate something like:
js> var a = makeDecimal();
js> var b = a.multiply("2.2");
where makeDecimal is a Java method returning a java.math.BigDecimal.
Whereas new java.math.BigDecimal() in Rhino causes Rhino to set up the
prototype, etc., simply returning a BigDecimal from a Java function
will not do so.