Groovy 数值类型包括整数类型和小数类型两种:
整数类型:byte、char、short、int、long、BigInteger
小数类型:float、double、BigDecimal
整数类型
byte a = 1 char b = 2 short c = 3 int d = 4 long e = 5 BigInteger f = 6
Groovy 在声明变量时可以不指定类型
// 在不声明数值类型时, 默认是 Integer 类型 def a1 = 1 assert a1 instanceof Integer // 大于 Integer.MAX_VALUE 2147483647, 默认是 Long 类型 def b1 = 2147483648 assert b1 instanceof Long // 大于 Long.MAX_VALUE 9223372036854775807, 默认是 BigInteger 类型 def c1 = 9223372036854775808 assert c1 instanceof BigInteger
小数类型
float a = 3.14 assert a instanceof Float double b = 3.14 assert b instanceof Double BigDecimal c = 3.14 assert c instanceof BigDecimal // 在不指定类型时,默认是 BigDecimal 类型 def d = 3.14 assert d instanceof BigDecimal
各数据类型后缀
各数值类型在声明时不指定类型,可以通过后缀表示该变量的类型
// Integer 后缀 i 或 I def a = 1I // Long 后缀 l 或 L def b = 1L // BigInteger 后缀 g 或 G def c = 1G // Float 后缀 f 或 F def e = 3.14F // Double 后缀 d 或 D def f = 3.14D // BigDecimal 后缀 g 或 G,BigInteger相同,取决于是不是小数 def g = 3.14G
其他进制数表示
只能用来表示整数类型
// 二进制数以 0b 为前缀 def a = 0b10101101 println(a) // 173 // 八进制数以 0 为前缀 def b = 0123 println(b) // 83 // 十六进制以 0x 为前缀 def c = 0xab println(c) // 171