Analysis of problems caused by data of BigDecimal type

Source: Internet
Author: User
Analysis of problems caused by data of BigDecimal type

Problem Description : The program needs to determine whether a field is 0 (the field type is BigDecimal), do not want to think, the object's judgment with equals? The result is a certain gap with the expected, see the code below and the results of the operation.

    public static void main(String[] args) {        BigDecimal decimal1 = BigDecimal.valueOf(0);        BigDecimal decimal2 = new BigDecimal("0.00");        System.out.println("the result is " +decimal1.equals(decimal2));    }

Operation Result:

the result is false

Conclusion: BigDecimal Type comparison equality cannot be achieved simply by means of the Equals method .

The Equals method of the BigDecimal class has the following source code:

    public boolean equals(Object x) {        if (!(x instanceof BigDecimal))            return false;        BigDecimal xDec = (BigDecimal) x;        if (x == this)            return true;        if (scale != xDec.scale)//这里会比较数字的精度            return false;        long s = this.intCompact;        long xs = xDec.intCompact;        if (s != INFLATED) {            if (xs == INFLATED)                xs = compactValFor(xDec.intVal);            return xs == s;        } else if (xs != INFLATED)            return xs == compactValFor(this.intVal);        return this.inflate().equals(xDec.inflate());    }

As you can see from the above note, the Equals method of the BigDecimal class will determine the accuracy of the numbers, and see the following code and the results of the operation:

    public static void main(String[] args) {        BigDecimal decimal1 = BigDecimal.valueOf(0).setScale(2);        BigDecimal decimal2 = new BigDecimal("0.00").setScale(2);        System.out.println("the result is " +decimal1.equals(decimal2));    }

Operation Result:

the result is true

Conclusion: when you use the Equals method of the BigDecimal class to determine data of two bigdecimal types, you need to set the precision, otherwise the result may be incorrect.

Think : It is difficult to set the accuracy each time, there are other ways to compare the same?

Look at the next BigDecimal method list, there is a method named CompareTo, through the note, it seems possible to compare different precision, see the code below.

    public static void main(String[] args) {        BigDecimal decimal1 = BigDecimal.valueOf(1.1);        BigDecimal decimal2 = new BigDecimal("1.10");        System.out.println("the result is " +decimal1.compareTo(decimal2));    }

Operation Result:

the result is 0

0 means two numbers are equal, and all of the two bigdecimal types that can achieve different precision through CompareTo are equal compared

problem : In the company's project, in order to avoid the problem caused by the loss of precision, all fields with precision requirements are bigdecimal type. The data persistence layer uses the MyBatis framework, and some of the conditions in the MyBatis mapper file are determined by the bigdecimal corresponding field, as follows:

<select id="selectByCondition" resultType="com.scove.demo.domain.Score">    select * from tb_score where 1=1     <if test="score!=null and score!=0">        and score&gt;#{score}    </if>    ...

Score is a bigdecimal type of field, score!=0 MyBatis How to judge, will not use the above equals method? If it is so project online will not poke big mess, think here, a little afraid of. Wrote a program to test, so write completely no problem, can achieve the purpose I want. But still a little worried, see how the bottom of mybatis is realized, so as not to make similar mistakes in the future.

After analysis and debugging, we quickly found the location of the key code, as follows:

public class ExpressionEvaluator {  public boolean evaluateBoolean(String expression, Object parameterObject) {    Object value = OgnlCache.getValue(expression, parameterObject);    if (value instanceof Boolean) {      return (Boolean) value;    }    if (value instanceof Number) {        return !new BigDecimal(String.valueOf(value)).equals(BigDecimal.ZERO);    }    return value != null;  }...
public final class OgnlCache {....  public static Object getValue(String expression, Object root) {    try {      Map<Object, OgnlClassResolver> context = Ognl.createDefaultContext(root, new OgnlClassResolver());      return Ognl.getValue(parseExpression(expression), context, root);    } catch (OgnlException e) {      throw new BuilderException("Error evaluating expression '" + expression + "'. Cause: " + e, e);    }  }

Use is the expression evaluation, OGNL This class unexpectedly did not have the source code, the Apache official net looked for under, IS has the corresponding source code, just need to download separately, really troublesome, forget not to look. It is said that the underlying use of spring's OGNL expression, I do not care. But later if you are not sure if the test in mapper is correct why did?

Think of the next, or write a tool class in doubt when the use of it, anyway, it is certainly very few when unsure, so casually write a simple bar, as follows:

    public static void main(String[] args) {        ExpressionEvaluator evaluator = new ExpressionEvaluator();        String expression = "score!=null and score!=0";        DynamicContext context = new DynamicContext(new Configuration(), null);        context.bind("score", BigDecimal.valueOf(0.1));        Boolean flag = evaluator.evaluateBoolean(expression , context.getBindings());        System.out.println("the result is " +flag);    }

Operation Result:

the result is true
Summarize

Development process, must be careful to deal with the details of the things, or accidentally jumped in the pit, light system caused inconsistent data, repair data, heavy is caused by major losses ....

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.