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

StackOverflow https://stackoverflow.com/questions/20550657

  •  01-09-2022
  •  | 
  •  

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

有帮助吗?

解决方案

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top