English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在此程序中,您将学习在Java中将给定数字四舍五入到小数点后n位。
public class Decimal {}} public static void main(String[] args) { double num = 1.34567; System.out.format("%.4f", num); } }
When running the program, the output is:
1.3457
在上面的程序中,我们使用format()方法将给定的浮点数打印num到4个小数位。.4f格式表示小数点后4位.
这意味着,最多只能在点后打印4个位置(小数位),f表示打印浮点数。
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 running the program, the output is:
1.346
In the above program, we use DecimalFormat class to round the given number num.
We use #, 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.