round()
方法将指定值四舍五入到最接近的 int 或 long 值并返回它。也就是说,3.87 被四舍五入为 4,3.24 被四舍五入为 3。
示例
class Main { public static void main(String[] args) { double a = 3.87; System.out.println(Math.round(a)); } } // Output: 4
Math.round() 的语法
round()
方法的语法是:
Math.round(value)
这里,
round()
是一个静态方法。因此,我们使用类名访问该方法,
Math
。
round() 参数
round()
方法接受一个参数。
注意: 值的数据类型应该是float或double。
round() 返回值
如果参数是float
,则返回 int
值
如果参数是 double
,则返回 long
值
round()
方法:
1.5 => 2 1.7 => 2
1.3 => 1
示例 1: Java Math.round() 与 double
class Main { public static void main(String[] args) { // Math.round() method // value greater than 5 after decimal double a = 1.878; System.out.println(Math.round(a)); // 2 // value equals to 5 after decimal double b = 1.5; System.out.println(Math.round(b)); // 2 // value less than 5 after decimal double c = 1.34; System.out.println(Math.round(c)); // 1 } }
示例 2: 带有浮点数的 Java Math.round()
class Main { public static void main(String[] args) { // Math.round() method // value greater than 5 after decimal float a = 3.78f; System.out.println(Math.round(a)); // 4 // value equals to 5 after decimal float b = 3.5f; System.out.println(Math.round(b)); // 4 // value less than 5 after decimal float c = 3.44f; System.out.println(Math.round(c)); // 3 } }