Table of Contents
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
1 2 3 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.