How to round up a number to two decimal places in Java?

In Java, you can use the Math.ceil() function to round up, and then use the DecimalFormat class to format the result with two decimal places.

Here is an example code:

import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        double number = 10.2345;
        
        // 向上取整
        double ceilNumber = Math.ceil(number);
        
        // 保留两位小数输出
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        String formattedNumber = decimalFormat.format(ceilNumber);
        
        System.out.println(formattedNumber);
    }
}

When running the code above, the output will be 11.00.

bannerAds