在 Java 中处理数字时,一个关键点就是区分整数(小数点后没有数字)和浮点数(小数点后有一位或多位数字)。
除了int和double,Java 还有其他数据类型:
// 8-Bit Integer
byte a = 127;
// 16-Bit Integer
short b = 262143;
// 64-Bit Integer
long d = 18446744073709551999L;
// 32-bit Single-Precision Floating-Point
float e = 5409.29f;
整数和浮点数都可以用_字符作为_数字分隔符_,在定义较大的数字时很有帮助:
int largeInt = 1_000_000;
// => 1000000
double largeDouble = 9_876_543.21;
// => 9876543.21
算术运算使用标准的算术运算符(+、-、* 等)。
数字可以用标准的比较运算符(<、>= 等)进行比较,也可以用相等运算符(==)和不等运算符(!=)。
5 * 6
// => 30
1.2 > 0.8
// => true
120 == 100
// => false
2 != 4
// => true
在数字类型之间转换时,有两种类型转换:
由于int的精度比double低,从int转换成double是安全的,因此属于隐式转换。
不过,从double转换成int可能会丢失数据,所以需要显式转换。
int i = 9;
double d = 2.72;
// Safe conversion, thus implicit conversion
double fromInt = i;
// Potentially unsafe conversion, thus explicit conversion
int fromDouble = (int)d;