1

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

code4jhon
  • 5,725
  • 9
  • 40
  • 60
  • So in other words, you are just saying if your BigDecimal is say 10, you want 10.00 and it's not producing the decimals? Really?? – Rob Dec 12 '13 at 17:56

2 Answers2

6

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).

Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
  • Ok, but I'm getting 12,00 instead of 12.00, do you know why? and I'm not configuring any specific locale. – code4jhon Dec 12 '13 at 18:01
  • Yes it's for your locale.. @Ingo i have the same strange locale ..check this quiestion for [help](http://stackoverflow.com/questions/5054132/how-to-change-the-decimal-separator-of-decimalformat-from-comma-to-dot-point) – nachokk Dec 12 '13 at 18:04
2

I am generating a CSV file

This means that you are not dealing with rounding - rather, you are dealing with formatting. In other words, it does not matter how many digits are there after the decimal point in the actual number: all you want is to put the proper number of digits in the text file that you are generating.

I've been required that all of the economic fields have 2 decimals.

One way of doing it is using printf's formatting capabilities:

BigDecimal bd = BigDecimal.valueOf(12.5);
System.out.printf("%.2f", bd);

demo.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523