温馨提示×

如何在Java中使用java四舍五入

小樊
81
2024-07-03 03:33:11
栏目: 编程语言

在Java中,可以使用Math.round()方法来实现四舍五入。该方法接受一个double类型的参数,并返回最接近该参数的long类型整数值。如果参数大于或等于0.5,则返回向上取整的值;如果参数小于0.5,则返回向下取整的值。

例如,下面的代码演示了如何使用Math.round()方法进行四舍五入:

double num1 = 10.4;
double num2 = 10.5;
double num3 = 10.6;

long roundedNum1 = Math.round(num1);
long roundedNum2 = Math.round(num2);
long roundedNum3 = Math.round(num3);

System.out.println("四舍五入结果:" + roundedNum1); // 输出10
System.out.println("四舍五入结果:" + roundedNum2); // 输出11
System.out.println("四舍五入结果:" + roundedNum3); // 输出11

在上面的代码中,num1被四舍五入为10,num2被四舍五入为11,num3被四舍五入为11。

0