Home > Enterprise >  How to use BigDecimal .equal() in java?
How to use BigDecimal .equal() in java?

Time:11-27

import java.math.BigDecimal;

public class test {
    public static void main(String[] args) {
        BigDecimal b1 = new BigDecimal("0.1");
        BigDecimal b2 = new BigDecimal("0.2");
        System.out.println(b1.multiply(b2));  // the result is 0.02 
        System.out.println(b1.multiply(b2).equals("0.02")); // boolean is false
        System.out.println(b1.add(b2)); //the result is 0.3
        System.out.println(b1.add(b2).equals("0.3")); // boolean is false
    }
};

I don't know why the .equals result is always false? thanks for answer.

CodePudding user response:

You are comparing BigDecimal to String.

Instead of

b1.add(b2).equals("0.3")

you should use

b1.add(b2).equals(new BigDecimal("0.3"))

CodePudding user response:

You are trying to compare BigDecimal with the String.

b1.multiply(b2).equals("0.02")

this statement will compare String "0.02" with the BigDecimal and as both the data types are different it is returning false.

create a new object of BigDecimal with the value "0.02" and pass it as parameter.

        BigDecimal b1 = new BigDecimal("0.1");
    BigDecimal b2 = new BigDecimal("0.2");
    System.out.println(b1.multiply(b2));  // the result is 0.02
    System.out.println(b1.multiply(b2).equals(new BigDecimal("0.02"))); // boolean is true as two same datatype objects are compared and both are equal.
    System.out.println(b1.add(b2)); //the result is 0.3
    System.out.println(b1.add(b2).equals("0.3")); // boolean is false because you are trying to compare a string and BigDecimal
  • Related