Math String Calculation with Spring SpelExpressionParser - too big values
Math String Calculation with Spring SpelExpressionParser - too big values
We are using the spring "SpelExpressionParser" for doing some math operations provided in a string.
Its working but there are some problems.
If one number in our math string is longer than an "int", we have to write an "L" behind the number. If we do not, the parser throws an exception (Number Format Exeption). That`s not good, cause then we have to split the string and write down an "L" after the number by ourself. Is there an option that the parser automaticly uses the correct datatype?
This provides an error
Operation: (-8069324632329525206) * 2
Error: Caused by: java.lang.NumberFormatException: For input string: "8069324632329525206"
This provides no error, but a WRONG result
Operation: (-8069324632329525206L) * 2
Result: 2308094809050501204
As you can see now, we have no more error but our result is just WRONG. It seems the parser is calculating with "Long" datatypes and our result may be out of range. In my opinion it`s not okay to get a WRONG result. There should be an error thrown instead...
So my question is:
Is there a another good math expression parser, which may uses "BigDecimal" or compatible datatypes so that I can do math calculation with very big numbers? Or is there an option to configure the spring parser correct?
1 Answer
1
One way to work around it is to explicitly use BigInteger
in the expression
BigInteger
#new java.math.BigInteger("8069324632329525206").multiply(2)
will calculate
16138649264659050412
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I tried it out. This works too: new java.math.BigDecimal("-8069324632329525206.34") * 2 But we have the case, that the user can write his own complex math expressions. This means I need to edit this expressions and replace numbers, bigger than "int" with the a string of a new biginteger or bigdecimal instance, like you showed. I hoped there would be an easier way or a good library which automaticly uses correct types. But thanks, at least this will help me out.
– Nils
Aug 23 at 15:37