Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is my code implementation to round BigDecimal values to two decimal places: 

BigDecimal rounded = value.round(new MathContext(2, RoundingMode.CEILING));

logger.trace("rounded {} to {}", value, rounded);

This is the respective output: 

rounded 0.819 to 0.82

rounded 1.092 to 1.1

rounded 1.365 to 1.4 // should be 1.37

rounded 2.730 to 2.8 // should be 2.74

rounded 0.819 to 0.82

The problem is it doesn’t round all the values. Can anyone tell me how to do this with BigDecimal or with another class/library? 

2 Answers

0 votes
by (19.7k points)

You can use RoundingMode to round the decimal value. 

my_value = my_value.setScale(2, RoundingMode.CEILING) 

If you want to learn more about Javathen go through this Java tutorial by Intellipaat for more insights.  

0 votes
by (3.1k points)

To round a BigDecimal in Java to always have two decimal places, you use the setScale method with RoundingMode. This way you will ensure that the result will have exactly two decimal places, rounding if needed. 

Example Code 

import java.math.BigDecimal; 

import java.math.RoundingMode; 

 

public class Main { 

    public static void main(String[] args) { 

        BigDecimal number = new BigDecimal("123.456"); 

BigDecimal rounded = number.setScale(2, RoundingMode.HALF_UP); // Rounds to two decimal places 

        System.out.println(rounded); // Output: 123.46 

    } 

} 

Explanation 

setScale(2, RoundingMode.HALF_UP) rounds BigDecimal to two decimal places. 

RoundingMode.HALF_UP rounds up if the third decimal is 5 or higher. 

This method guarantees two-decimal formatting. 

Related questions

0 votes
1 answer
asked Jul 9, 2019 in SQL by Tech4ever (20.3k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 19, 2019 in RPA by noah kapoor (5.3k points)
0 votes
1 answer
asked Apr 14, 2021 in Java by Jake (7k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...