English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)

Java Reader/Writer

Java Other Topics

Java program rounds numbers to n decimal places

Java Examples Comprehensive

In this program, you will learn how to round a given number to n decimal places in Java.

Example1Use formatting to round numbers

public class Decimal {}}
    public static void main(String[] args) {
        double num = 1.34567;
        System.out.format("%.4f, num);
    }
}

When the program is run, the output is:

1.3457

In the above program, we use the format() method to print the given floating-point number num to4decimal places.4The f format indicates the decimal places after4digits.

This means that at most onlyat the decimal pointAfter printing4positions (decimal places), f indicates printing a floating-point number.

Example2Use DecimalFormat to round numbers

import java.math.RoundingMode;
import java.text.DecimalFormat;
public class Decimal {}}
    public static void main(String[] args) {
        double num = 1.34567;
        DecimalFormat df = new DecimalFormat("#.###");
        df.setRoundingMode(RoundingMode.CEILING);
        System.out.println(df.format(num));
    }
}

When the program is run, the output is:

1.346

In the above program, we use DecimalFormat class to round the given number num.

We use #, the pattern declaration format #.###. This means that we want num to have at most3decimal places. We will also set the rounding mode to Ceiling, which will cause the last given position to be rounded up to the next number.

Therefore, the1.34567rounded to the decimal point after3digit will be printed1.346, the6The digit is the3decimal places5the next number.

Java Examples Comprehensive