Search code examples
javaroundingbigdecimal

Big Decimal Round to two decimals ALWAYS (even if my BigDecimal object has no decimals)?


How can I round BigDecimal objects to 2 decimals always (even if my BigDecimal object has no decimals)?

I'm doing:

myBigDecimal.setScale(2, RoundingMode.HALF_UP); // works fine when it has decimals

Context: I have a List of POJO's that when I send to the front end I give them format in ExtJs

BUT

I am generating a CSV file also and I've been required that all of the economic fields have 2 decimals.

Any ideas or work arounds?

Thx


Solution

  • You can use the java.text.DecimalFormat class to format decimal numbers. e.g.

    Code:

    public static void main(String[] args) {
        DecimalFormatSymbols symbols = new DecimalFormatSymbols();
        symbols.setDecimalSeparator('.');
        DecimalFormat formatter = new DecimalFormat("#.00", symbols);
        System.out.println(formatter.format(BigDecimal.valueOf(12.456)));
        System.out.println(formatter.format(BigDecimal.valueOf(12L)));
    }
    

    Output:

    12.46
    12.00
    

    See more in Customizing Formats (The Java Tutorials > Internationalization > Formatting).