Java 中的 Float 比较
要比较 Java 中的 Float,请使用以下方法 −
方法 1 − Java 中的 compareTo(newFloat) 方法
java.lang.Float.compareTo() 方法比较两个 Float 对象。此方法如果 new float 值在此 Float 中以数值相等,则返回 0;如果此 Float 在以数值上小于 new float,则返回小于 0 的值;如果此 Float 在以数值上大于 new float,则返回大于 0 的值。
示例如下 −
示例
import java.lang.*;
public class Demo {
public static void main(String args[]) {
Float f1 = new Float("25.2");
Float f2 = new Float("25.20");
int res = f1.compareTo(f2);
if(res > 0) {
System.out.println("f1 is greater than f2");
}
else if(res < 0) {
System.out.println("f1 is less than f2");
}
else {
System.out.println("f1 is equal to f2");
}
}
}输出
f1 is equal to f2
方法 2 − Java 中的 compare(f1, f2) 方法
java.lang.Float.compare() 方法以数值比较两个 float 值对象。如果 f1 在以数值上等于 f2,则此方法返回 0;如果 f1 在以数值上小于 f2,则返回小于 0 的值;如果 f1 在以数值上大于 f2,则返回大于 0 的值。
我们来看一个示例 −
示例
import java.lang.*;
public class Demo {
public static void main(String args[]) {
float f1 = 29.29f;
float f2 = 55.55f;
int res = Float.compare(f1, f2);
if(res > 0) {
System.out.println("f1 is greater than f2");
}
else if(res < 0) {
System.out.println("f1 is less than f2");
}
else {
System.out.println("f1 is equal to f2");
}
}
}输出
f1 is less than f2
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP