Set Decimal Place of a Big Decimal Value in Java


We have the following BigDecimal value −

BigDecimal val1 = new BigDecimal("37578975587.876876989");

We have set the decimal place to be −

int decPlaces1 = 3;

Now, we will use the ROUND_DOWN field to set the rounding mode to round towards zero −

// ROUND_DOWN
val1 = val1.setScale(decPlaces1, BigDecimal.ROUND_DOWN);
String str1 = val1.toString();
System.out.println("Result = "+str1);

To set decimal place of a BigDecimal value in Java, try the following code −

Example

 Live Demo

import java.math.BigDecimal;
public class Demo {
   public static void main(String[] argv) throws Exception {
      int decPlaces1 = 3;
      int decPlaces2 = 5;
      BigDecimal val1 = new BigDecimal("37578975587.876876989");
      BigDecimal val2 = new BigDecimal("62567875598.976876569");
      System.out.println("Value 1 : "+val1);
      System.out.println("Value 2 : "+val2);
      // ROUND_DOWN
      val1 = val1.setScale(decPlaces1, BigDecimal.ROUND_DOWN);
      String str1 = val1.toString();
      System.out.println("Result = "+str1);
      // ROUND_UP
      val2 = val2.setScale(decPlaces2, BigDecimal.ROUND_UP);
      String str2 = val2.toString();
      System.out.println("Result = "+str2);
   }
}

Output

Value 1 : 37578975587.876876989
Value 2 : 62567875598.976876569
Result = 37578975587.876
Result = 62567875598.97688

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements