English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java Math mathematical methods
Java Math round()方法将指定的值四舍五入为最接近的int或long值,然后将其返回。
也就是说,1.2四舍五入为1,1.8四舍五入为2。
round()方法的语法为:
Math.round(value)
注意:round()是静态方法。因此,我们可以使用类名Math来访问该方法。
value -要四舍五入的数字
注意:该值的数据类型应为float或double。
如果参数为float,则返回int值
如果参数为double,则返回long值
round()方法:
如果小数点后的值大于或等于5,则向上舍入
1.5 => 2 1.7 => 2
如果小数点后的值小于5,则向下舍入
1.3 => 1
class Main { public static void main(String[] args) { // Math.round() method //The value after the decimal point is greater than5 double a = 1.878; System.out.println(Math.round(a)); // 2 //The value after the decimal point is equal to5 double b = 1.5; System.out.println(Math.round(b)); // 2 //The value after the decimal is less than5 double c = 1.34; System.out.println(Math.round(c)); // 1 } }
class Main { public static void main(String[] args) { // Math.round() method //The value after the decimal point is greater than5 float a = 3.78f; System.out.println(Math.round(a)); // 4 //The value after the decimal point is equal to5 float b = 3.5f; System.out.println(Math.round(b)); // 4 // The value after the decimal is less than5 float c = 3.44f; System.out.println(Math.round(c)); // 3 } }