How to use comparison operators like >, =, < on BigDecimal

后端 未结 8 1182
清酒与你
清酒与你 2021-01-30 11:54

I have a domain class with unitPrice set as BigDecimal data type. Now I am trying to create a method to compare price but it seems like I can\'t have comparison operators in Big

相关标签:
8条回答
  • 2021-01-30 13:00

    Here is an example for all six boolean comparison operators (<, ==, >, >=, !=, <=):

    BigDecimal big10 = new BigDecimal(10);
    BigDecimal big20 = new BigDecimal(20);
    
    System.out.println(big10.compareTo(big20) < -1);  // false
    System.out.println(big10.compareTo(big20) <= -1); // true
    System.out.println(big10.compareTo(big20) == -1); // true
    System.out.println(big10.compareTo(big20) >= -1); // true
    System.out.println(big10.compareTo(big20) > -1);  // false
    System.out.println(big10.compareTo(big20) != -1); // false
    
    System.out.println(big10.compareTo(big20) < 0);   // true
    System.out.println(big10.compareTo(big20) <= 0);  // true
    System.out.println(big10.compareTo(big20) == 0);  // false
    System.out.println(big10.compareTo(big20) >= 0);  // false
    System.out.println(big10.compareTo(big20) > 0);   // false
    System.out.println(big10.compareTo(big20) != 0);  // true
    
    System.out.println(big10.compareTo(big20) < 1);   // true
    System.out.println(big10.compareTo(big20) <= 1);  // true
    System.out.println(big10.compareTo(big20) == 1);  // false
    System.out.println(big10.compareTo(big20) >= 1);  // false
    System.out.println(big10.compareTo(big20) > 1);   // false
    System.out.println(big10.compareTo(big20) != 1);  // true
    
    0 讨论(0)
  • 2021-01-30 13:00

    This thread has plenty of answers stating that the BigDecimal.compareTo(BigDecimal) method is the one to use to compare BigDecimal instances. I just wanted to add for anymore not experienced with using the BigDecimal.compareTo(BigDecimal) method to be careful with how you are creating your BigDecimal instances. So, for example...

    • new BigDecimal(0.8) will create a BigDecimal instance with a value which is not exactly 0.8 and which has a scale of 50+,
    • new BigDecimal("0.8") will create a BigDecimal instance with a value which is exactly 0.8 and which has a scale of 1

    ... and the two will be deemed to be unequal according to the BigDecimal.compareTo(BigDecimal) method because their values are unequal when the scale is not limited to a few decimal places.

    First of all, be careful to create your BigDecimal instances with the BigDecimal(String val) constructor or the BigDecimal.valueOf(double val) method rather than the BigDecimal(double val) constructor. Secondly, note that you can limit the scale of BigDecimal instances prior to comparing them by means of the BigDecimal.setScale(int newScale, RoundingMode roundingMode) method.

    0 讨论(0)
提交回复
热议问题