BigDecimal Comparison Returns Unexpected Result

3

In one of my methods I make the following comparison, as in the example below:

public static void main(String[] args) {

    BigDecimal valor = new BigDecimal("100");
    exemplo(valor);

}

public static void exemplo(BigDecimal valor) {
    if (valor.compareTo(new BigDecimal("50.000")) == 1 || valor.compareTo(new BigDecimal("50.000")) == 0) {
        System.out.println("número maior");
    }
}

Passing "100" as a parameter, the problem is that the BigDecimal class ends up with a value of "100" greater than the value "50,000", I tried to pass the value as: "50.000.00" to try to solve the problem , but the class does not allow me to do this, any solution?

    
asked by anonymous 27.03.2016 / 01:09

2 answers

4

You're actually comparing 100 to 50. In English, the dot separates the integer part of the fractional part of a number instead of the comma. As indicated in the official documentation >, BigDecimal accepts fractional numbers represented in this way in its constructor. It is what you are doing without seeing.

To do what you want, compare to "50000".

    
27.03.2016 / 01:22
5

The dot is the decimal separator, so you are comparing 100 to 50 (50,000 read "in Portuguese" is 50,000, or simply 50). Do not use stitches to make a thousand separations. Actually this does not exist in programming. See:

public static void exemplo(BigDecimal valor) {
    if (valor.compareTo(new BigDecimal("50000")) == 1 || valor.compareTo(new BigDecimal("50000")) == 0) {
        System.out.println("número maior");
    }
}

It works perfectly.

The reason for not accepting 50.000.00 is because it has two decimal separators, or for what we use here in Brazil, it's like having two commas, which a number can not have.

I imagine that your real problem is getting a value like string and it has decimal places. Then you must convert the value to BigDecimal according to the pattern you receive. It's quite another thing.

public static void exemplo(BigDecimal valor) {
    try {
        DecimalFormat df = new DecimalFormat("###,##0", new DecimalFormatSymbols (new Locale ("pt", "BR")));
        df.setParseBigDecimal(true);
        BigDecimal decimal = (BigDecimal)df.parse("50.000");
        if (valor.compareTo(decimal) == 1 || valor.compareTo(decimal) == 0) {
            System.out.println("número maior");
        } else {
            System.out.println("número menor");
        }
    } catch (ParseException e) { //só para facilitar, não faça isto
        e.printStackTrace();
    }
}

See running on ideone .

    
27.03.2016 / 01:25