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); } }
이 프로그램을 실행할 때, 출력은 다음과 같습니다:
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)); } }
이 프로그램을 실행할 때, 출력은 다음과 같습니다:
1.346
위의 프로그램에서 우리는 DecimalFormat 클래스를 사용하여 주어진 숫자 num을 반올림합니다.
우리는 #를 사용하여 모드를 선언합니다. #.###. 이는 num이 최대3개의 소수점 자리수를 반올림합니다. 또한, 반올림 모드를 Ceiling로 설정하여 마지막 주어진 위치가 다음 숫자로 반올림됩니다.
따라서,1.34567소수점 뒤의3자리수를 출력합니다.1.346번, 제6자리는 제3자리수 소수점5의 다음 숫자.