FinExpr: 一个表达式计算工具（支持添加自定义函数和变量）

Brief introduction

FinExpr is an expression evaluator implemented by Java. Focus on precision, can be used in financial system.

FinExpr是一个Java语言实现的表达式求值工具包。名称Fin是finance的缩写，注重于精度，适用于金融、计费、财务相关对金额精度敏感的系统。在计算时为了避免double类型的数据误差，默认均采用BigDecimal进行计算。 Maven Repo: https://search.maven.org/artifact/io.github.jarvisjin/fin-expr/1.0.1/jar

Usage

``````<dependency>
<groupId>io.github.jarvisjin</groupId>
<artifactId>fin-expr</artifactId>
<version>1.0.1</version>
</dependency>``````

``````dependencies {
...
compile 'io.github.jarvisjin:fin-expr:1.0.1'
}``````

Expression: io.github.jarvisjin.finexpr.expr.Expression

Simple Example: 简单示例

``````Expression e = new Expression("345000*0.0157");
BigDecimal result = e.calculate(); // result 5416.5000``````

Custom Function & Add variables: 使用自定义函数 min()、使用变量 x, y, a, b

``````Expression e = new Expression("min(x,y) + a^b");

// define function "min"
@Override
public BigDecimal apply(List<BigDecimal> args, MathContext mc) {
if(args.get(0).compareTo(args.get(1))<0) {
return args.get(0);
}else {
return args.get(1);
}
}
});

/*
*  set variables,
*  in this case:
*  the expression
*  = min(8.5,5.77) + 5^3
*  = 5.77 + 5^3
*  = 5.77 + 125
*  = 130.77
*/

BigDecimal result = e.calculate(); // 130.77

/*
* set replaceOnDuplicate==true, to replace the value of x and b, then caculate again.
* the expression
* = -9 + 5^5
* = -9 + 3125
* = 3116
*
* if you don't want to use replaceOnDuplicate, you can use Expression.clearVariables() instead.
* that function will clean all variables, and you need to reset all of the variables;
*/
result = e.calculate(); // 3116``````

Custom Precision & RoundingMode: 自定义精度和舍入模式

``Expression e = new Expression("0.07*2.59", new MathContext(25,RoundingMode.HALF_UP));``

实际应用场景：

``````Expression e = new Expression("pmt(0.1, 12, 10000)");

@Override
public BigDecimal apply(List<BigDecimal> args, MathContext mc) {
// implement of pmt();
// https://support.office.com/en-us/article/PMT-function-0214da64-9a63-4996-bc20-214433fa6441
}
});
BigDecimal result = e.calculate();    // result: 计算借款10000元 12期还 年化利率10%，等额本息每期还款金额

// 比如有计费公式是向贷款商户收取每期还款金额的 0.2%作为服务费, 则表达式Expression改成 0.002*pmt(利率, 期数, 本金) 即可
Expression e = new Expression("0.002*pmt(0.1, 12, 10000)");
``````

Default Supported Operators

Operator Description
+ Additive operator / Unary plus
- Subtraction operator / Unary minus
* Multiplication operator
/ Division operator
^ Power operator

Tips: currently the symbol of operator can only be one character.

Fin Expr

A expression evaluator for Java. Focus on precision, can be used in financial system.

Fin Expr Info

⭐ Stars 25
🔗 Source Code github.com
🕒 Last Update 7 months ago
🕒 Created 5 years ago
🐞 Open Issues 1
➗ Star-Issue Ratio 25
😎 Author JarvisJin