English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to round a given number to n decimal places in Java.
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.
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.