How to round a number in Java and keep two decimal places?

In Java, you can round and keep two decimal places using the DecimalFormat class.

Here is a sample code:

import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        double number = 3.1415926;
        
        // 创建DecimalFormat对象,并设置保留小数点后两位
        DecimalFormat df = new DecimalFormat("#.00");
        
        // 使用format方法进行四舍五入并保留小数点后两位
        String result = df.format(number);
        
        System.out.println(result);
    }
}

The output result is 3.14.

bannerAds