Search code examples
javanumber-formattingbigdecimal

Is there a way to assign a formatted BigDecimal number to a BigDecimal?


I have a piece of code which has two BigDecimal variables. Both the variables are sent to the method format(which works fine) and then printed. The variable "d" is sent to the format method and then printed directly without assigning it(since the method format returns a string). The problem occurs in the variable a, where I assign the formatted value(which is a String), convert to a bigDecimal and then store in variable a. The format is kept when I print the value of a, but the format is not there when I print the variable d. How can I assign the formatted value without losing its format to a BigDecimal variable?

public static void main(String[] args) {
    BigDecimal d = new BigDecimal("0.0005");
    BigDecimal a = new BigDecimal(format(d, 2));

    System.out.println(a); // 0.000500
    System.out.println(format(new BigDecimal("0.00001"), 3)); // 1.000E-5
}

private static String format(BigDecimal x, int scale) {
    NumberFormat formatter = new DecimalFormat("0.0E0");
    formatter.setRoundingMode(RoundingMode.HALF_UP);
    formatter.setMinimumFractionDigits(scale);
    return formatter.format(x);
}

Solution

  • Numbers (no matter what kind of - BigDecima, Float,Long) are to store values (most accurate ones) not their String representation. You cannot "store formatted value" as number and expect it to be represented that way all the time. Everytime you want to have formatted value, you have to format it.

    so here

    BigDecimal a = new BigDecimal(format(d, 2));
    

    you are just creating new BigDecimal using some formatted number which is a string. That string is parsed back to the number and thats it.

    What you expect to happen is similar to saying that you want "string" to be stored "as is" in binary system - as this is how numbers are stored physically. Nope, it will still be bunch of ones and zeroes.