How to Round to at Most 2 Decimal Places in Java

Jan 13, 2024

1 min read

Published in

Rounding Numbers to Two Decimal Places in Java

In Java, rounding numbers to two decimal places is a common task. This can be achieved using the BigDecimal class, which provides precise arithmetic and rounding capabilities. Here’s a simple code snippet to demonstrate how to round a double to two decimal places:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import java.math.BigDecimal;

public class DecimalRounder {

    public static double roundToTwoDecimalPlaces(double value) {
        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();
    }

    public static void main(String[] args) {
        double originalValue = 123.45678;
        double roundedValue = roundToTwoDecimalPlaces(originalValue);

        System.out.println("Original Value: " + originalValue);
        System.out.println("Rounded Value: " + roundedValue);
    }
}

Explanation:

  1. Import BigDecimal: Begin by importing the BigDecimal class, which will be used for precise arithmetic.

  2. Define roundToTwoDecimalPlaces method: This method takes a double value as input, converts it to a BigDecimal, and then rounds it to two decimal places using setScale with ROUND_HALF_UP rounding mode.

  3. Example in main method: The main method demonstrates how to use the roundToTwoDecimalPlaces method with an example value. It prints the original and rounded values.

This code uses ROUND_HALF_UP rounding mode, which rounds towards “nearest neighbor” unless both neighbors are equidistant, in which case, it rounds up. Adjust the rounding mode as needed based on your requirements.

Sharing is caring!