Saturday 11 April 2020

Round BigDecimal to n decimal places

Using 'setScale' method of BigDecimal, you can specify the scale of the BigDecimal value to be returned.

For example, below snippet rounnd the decimal to 2 digits after '.'.
BigDecimal roundedValue = actualValue.setScale(2, RoundingMode.CEILING);

Find the below working application.

App.java
package com.sample.app;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class App {

 public static void main(String args[]) {
  BigDecimal[] bigDecimals = new BigDecimal[5];
  
  bigDecimals[0] = new BigDecimal("0.81934");
  bigDecimals[1] = new BigDecimal("0.5");
  bigDecimals[2] = new BigDecimal("0.564");
  bigDecimals[3] = new BigDecimal("0.54321");
  bigDecimals[4] = new BigDecimal("0.678951");
  
  System.out.println("Actual Value, Rounded Value");
  for(int i = 0; i < bigDecimals.length; i++) {
   BigDecimal actualValue = bigDecimals[i];
   BigDecimal roundedValue = actualValue.setScale(2, RoundingMode.CEILING);
   
   System.out.println(actualValue + "," + roundedValue);
  }
 }
}

Output

Actual Value, Rounded Value
0.81934,0.82
0.5,0.50
0.564,0.57
0.54321,0.55
0.678951,0.68



You may like

No comments:

Post a Comment