Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

BigDecimal round

In this tutorial we will see about BigDecimal‘s round method. BigDecimal’s round method is used to round the Bigdecimal based on MathContext setting.

Syntax

public BigDecimal	round ( MathContext  mc)

Return type

returns BigDecimal rounded with MathContext setting

BigDecimal round example

Let’s understand BigDecimal method with the help of example

import java.math.*;
package org.arpit.java2blog;

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

public class BigDecimalRoundMain {

	public static void main(String[] args) {
		BigDecimal bigdecimal1 = new BigDecimal("80.23776");
		MathContext mc1=new MathContext(4);
		BigDecimal roundedBigDecimal1=bigdecimal1.round(mc1);
		System.out.println("80.23776 is rounded to: "+roundedBigDecimal1.toString());
		
		// You can specify RoundingMode too with MathContext object
		MathContext mc2=new MathContext(4,RoundingMode.FLOOR);
		BigDecimal roundedBigDecimal2=bigdecimal1.round(mc2);
		System.out.println("80.23776 is rounded to: "+roundedBigDecimal2.toString()+"  with help of RoundingMode");
	}
}

Above program will generate below output.

80.23776 is rounded to: 80.24
80.23776 is rounded to: 80.23 with help of RoundingMode

BigDecimal setScale method

You can use setScale method also to round BigDecimal.Let’s understand with the help of example.

package org.arpit.java2blog;

import java.math.BigDecimal;

public class BigDecimalRoundMain {

	public static void main(String[] args) {
		
		BigDecimal b = new BigDecimal("12.4567");
		b=b.setScale(3, BigDecimal.ROUND_HALF_UP);
		System.out.println("BigDecimal Rounding to 3 decimal places: "+b);
	}
}

When you run above program, you will get below output.

BigDecimal Rounding to 3 decimal places: 12.457

That’s all about BigDecimal round method.

The post BigDecimal round appeared first on Java2Blog.



This post first appeared on How To Learn Java Programming, please read the originial post: here

Share the post

BigDecimal round

×

Subscribe to How To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×