在 Java 中舍入浮点数和双精度数
为了在 Java 中舍入浮点数和双精度数,我们使用 java.lang.Math.round() 方法。该方法接受 double 或 float 值并返回一个整数值。它返回最接近 number 的整数。这是通过在该数字上添加 ½ 然后对其取整来计算的。
声明 - java.lang.Math.round() 方法声明如下 -
public static int round(float a) public static int round(double a)
其中 a 是要舍入的值。
我们来看看一个在 Java 中舍入浮点数和双精度数的程序。
示例
import java.lang.Math;
public class Example {
public static void main(String[] args) {
// declaring and initializing some double and values
double x = 25.5;
float y = 8.1f;
// printing the rounded values
System.out.println("The round-off of "+ x + " is "+ Math.round(x));
System.out.println("The round-off of "+ y + " is "+ Math.round(y));
}
}输出
The round-off of 25.5 is 26 The round-off of 8.1 is 8
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP