Friday 13 March 2020

How to compare two BigDecimals?

Using compareTo function of BigDecimal you can compare, whether two decimals are equal, less than or greater than other.
private static void compare(BigDecimal decimal1, BigDecimal decimal2) {
 if (decimal1.compareTo(decimal2) == 1) {
  System.out.println(decimal1 + " is greater than " + decimal2);
 } else if (decimal1.compareTo(decimal2) == 0) {
  System.out.println(decimal1 + " is equal to " + decimal2);
 } else {
  System.out.println(decimal1 + " is less than " + decimal2);
 }
}

Find the below working application.

App.java
package com.sample.app;

import java.math.BigDecimal;

public class App {

 private static void compare(BigDecimal decimal1, BigDecimal decimal2) {
  if (decimal1.compareTo(decimal2) == 1) {
   System.out.println(decimal1 + " is greater than " + decimal2);
  } else if (decimal1.compareTo(decimal2) == 0) {
   System.out.println(decimal1 + " is equal to " + decimal2);
  } else {
   System.out.println(decimal1 + " is less than " + decimal2);
  }
 }

 public static void main(String[] args) {
  BigDecimal decimal1 = new BigDecimal("0.001");
  BigDecimal decimal2 = new BigDecimal("0.00");
  BigDecimal decimal3 = new BigDecimal("1");
  BigDecimal decimal4 = new BigDecimal("-1");

  compare(decimal1, BigDecimal.ZERO);
  compare(decimal1, decimal2);
  compare(decimal1, decimal3);
  compare(decimal1, decimal4);

 }

}

Output

0.001 is greater than 0
0.001 is greater than 0.00
0.001 is less than 1
0.001 is greater than -1


You may like

No comments:

Post a Comment