Format BigDecimal as String with max 2 decimal digits

In this post, I will be sharing how to format BigDecimal as String with max 2 decimal digits. There are two ways to achieve our goal:

1. Exactly 2 decimal digits

2. Max 2 decimal digits

Read Also: Convert BigDecimal to String in Java

Format BigDecimal as String with max 2 decimal digits

1. Exactly 2 decimal digits


We can easily format BigDecimal as String to exactly 2 decimal digits with the help of DecimalFormat as shown below in the examples:

Example 1: Using new DecimalFormat("0.00")

import java.math.BigDecimal;
import java.text.DecimalFormat;
public class FormatBigDecimal {
    public static void main(String args[]) {
      BigDecimal bd = new BigDecimal("23445564.4664327348934");
      String result = new DecimalFormat("0.00").format(bd);
      System.out.println("Exactly 2 decimal digits: " + result);
    }
}


Output:
Exactly 2 decimal digits: 23445564.47


Example 2: Using DecimalFormat methods

import java.text.DecimalFormat;
import java.math.BigDecimal;
public class FormatBigDecimal2 {
    public static void main(String args[]) {
      BigDecimal bd2 = new BigDecimal("32498567845.479346823");
      DecimalFormat df = new DecimalFormat();
      df.setMaximumFractionDigits(2);
      df.setMinimumFractionDigits(2);
      String result2 = df.format(bd2);
      System.out.println("Exactly 2 decimal digits: " + result2);
    }
}


Output:
Exactly 2 decimal digits: 32,498,567,845.48


2. Max 2 decimal digits


We can format BigDecimal as String with max 2 decimal digits as shown below in the examples:

Example 1: Using DecimalFormat methods

import java.text.DecimalFormat;
import java.math.BigDecimal;
public class FormatBigDecimal3 {
    public static void main(String args[]) {
      BigDecimal bd3 = new BigDecimal("8793457894378.29845");
      DecimalFormat df = new DecimalFormat();
      df.setMaximumFractionDigits(2);
      df.setMinimumFractionDigits(0);
      String result3 = df.format(bd3);
      System.out.println("Max 2 decimal digits: " + result3);
    }
}


Output:
Max 2 decimal digits: 8,793,457,894,378.3


Example 2: Using NumberFormat methods

import java.text.NumberFormat;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class FormatBigDecimal4 {
    public static void main(String args[]) {
      BigDecimal bd4 = new BigDecimal("8793457894378.7");
      bd4 = bd4.setScale(2, RoundingMode.DOWN);
      String result4 = NumberFormat.getNumberInstance(java.util.Locale.US).format(bd4);
      System.out.println("Max 2 decimal digits: " + result4);
    }
}


Output:
Max 2 decimal digits: 8,793,457,894,378.7


That's all for today. Please mention in the comments if you have any questions related to how to format BigDecimal as String with max 2 decimal digits.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry