温馨提示×

Java中round函数如何进行四舍五入

小樊
109
2024-08-24 02:05:30
栏目: 编程语言

在Java中,可以使用Math.round()函数来进行四舍五入操作。这个函数接受一个浮点数作为参数,并返回最接近该浮点数的整数,如果有两个整数与该浮点数的距离相等,则返回最接近正无穷大的那个整数。

例如,可以使用以下代码进行四舍五入操作:

double num = 3.5; long roundedNum = Math.round(num); System.out.println(roundedNum); // 输出4 double num2 = 3.4; long roundedNum2 = Math.round(num2); System.out.println(roundedNum2); // 输出3 

在这个例子中,3.5会被四舍五入为4,而3.4会被四舍五入为3。

0