菜鸟话Java---Number接口详解

Number类

转自这里

大多数时候,在使用java中的数字时,我们使用原始数据类型。但是,Java还在java.lang包中的抽象类Number下提供了各种数字包装子类。Number类下主要有6个子类。这些子类定义了一些在处理数字时经常使用的有用方法。byte, integer, double, short, float, long

为什么要在原始数据上使用Number类对象?

数字类定义的常量(如MIN_VALUE和MAX_VALUE)提供数据类型的上限和下限,非常有用。
Number类对象可以用作期望对象的方法的参数(通常用于处理数字集合)。
类方法可用于将值转换为其他基本类型以及从其他基本类型转换值,用于转换字符串和从字符串转换,以及用于在数字系统(十进制,八进制,十六进制,二进制)之间进行转换。

Number的所有子类通用的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
xxx xxxValue():这里xxx表示原始数字数据类型(byteshortintlongfloatdouble)。此方法用于将此 Number对象的值转换为指定的基本数据类型。 
句法 :
byte byteValue()
short shortValue()
int intValue()
long longValue()
float floatValue()
double doubleValue()
参数:
----
返回:
此对象表示的数值
转换为指定类型后

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//Java program to demonstrate xxxValue() method
public class Test
{
public static void main(String[] args)
{
// Creating a Double Class object with value "6.9685"
Double d = new Double("6.9685");

// Converting this Double(Number) object to
// different primitive data types
byte b = d.byteValue();
short s = d.shortValue();
int i = d.intValue();
long l = d.longValue();
float f = d.floatValue();
double d1 = d.doubleValue();

System.out.println("value of d after converting it to byte : " + b);
System.out.println("value of d after converting it to short : " + s);
System.out.println("value of d after converting it to int : " + i);
System.out.println("value of d after converting it to long : " + l);
System.out.println("value of d after converting it to float : " + f);
System.out.println("value of d after converting it to double : " + d1);
}
}
输出:
value of d after converting it to byte : 6
value of d after converting it to short : 6
value of d after converting it to int : 6
value of d after converting it to long : 6
value of d after converting it to float : 6.9685
value of d after converting it to double : 6.9685

注意:转换时,可能会发生精度损失。例如,我们可以看到在从Double对象转换为int数据类型时,小数部分(“.9685”)已被省略。