Kotlin 숫자 νƒ€μž…

Kotlin 숫자 νƒ€μž…

μ •μˆ˜ νƒ€μž…

νƒ€μž… 크기 (bits) μ΅œμ†Œκ°’ μ΅œλŒ€κ°’
Byte 8 -128 127
Short 16 -32,768 (-2^15) 32,767 (2^15 - 1)
Int 32 -2,147,483,648 (-2^31) 2,147,483,647 (2^31 - 1)
Long 64 -9,223,372,036,854,775,808 (-2^63) 9,223,372,036,854,775,807 (2^63 - 1)

μ •μˆ˜λ‘œ μ•”μ‹œμ  μ„ μ–Έλœ λ³€μˆ˜ 쀑 Int μ΅œλŒ€κ°’ μ΄ν•˜μ˜ 값은 Intνƒ€μž…μœΌλ‘œ μ„ μ–Έλ˜λ©°, Int μ΅œλŒ€κ°’μ„ μ΄ˆκ³Όν•˜λŠ” κ²½μš°λŠ” Long νƒ€μž…μœΌλ‘œ μ„ μ–Έλœλ‹€. Long으둜 μ„ μ–Έν•˜κ³  μ‹Άλ‹€λ©΄ L suffixλ₯Ό 뢙이면 λœλ‹€.

val one = 1 // Int
val threeBillion = 3000000000 // Long
val oneLong = 1L // Long
val oneByte: Byte = 1

μ‹€μˆ˜ νƒ€μž…

νƒ€μž… 크기 (bits) Significant bits Exponent bits Decimal digits
Float 32 24 8 6-7
Double 64 53 11 15-16

μ†Œμˆ˜μ μ΄ μžˆλŠ” 수λ₯Ό μ„ μ–Έν•˜μ—¬ Doulbe λ˜λŠ” Float νƒ€μž…μ„ μ •μ˜ν•  수 μžˆλ‹€. μ†Œμˆ˜μ μ΄ μžˆλŠ” μˆ˜λŠ” μ»΄νŒŒμΌλŸ¬κ°€ Double νƒ€μž…μœΌλ‘œ μΆ”λ‘ ν•˜λ©°, f λ˜λŠ” F suffixλ₯Ό λΆ™μ΄κ±°λ‚˜, 6-7 κ°œκ°€ λ„˜λŠ” μˆ˜κ°€ ν¬ν•¨λ˜λ©΄ Float νƒ€μž…μœΌλ‘œ μΆ”λ‘ ν•œλ‹€.

val pi = 3.14 // Double
// val one: Double = 1 // Error: type mismatch
val oneDouble = 1.0 // Double

val e = 2.7182818284 // Double
val eFloat = 2.7182818284f // Float

λ‹€λ₯Έ μ–Έμ–΄λ“€κ³Ό λ‹€λ₯΄κ²Œ, Kotlin은 μ•”μ‹œμ μœΌλ‘œ 숫자λ₯Ό ν™•μž₯ν•˜μ—¬ λ³€ν™˜ν•΄μ£Όμ§€ μ•ŠλŠ”λ‹€. 예λ₯Ό λ“€μ–΄, Double νŒŒλΌλ―Έν„°λ₯Ό λ°›λŠ” ν•¨μˆ˜λŠ” Double νƒ€μž…λ§ŒμœΌλ‘œλ§Œ 호좜 κ°€λŠ₯ν•˜λ‹€.

fun main() {
    fun printDouble(d: Double) { print(d) }

    val i = 1
    val d = 1.0
    val f = 1.0f

    printDouble(d)
//    printDouble(i) // Error: Type mismatch
//    printDouble(f) // Error: Type mismatch
}

λ‹€λ₯Έ νƒ€μž…μœΌλ‘œ λ³€ν™˜ν•  λ•ŒλŠ” λͺ…μ‹œμ  λ³€ν™˜μ„ μ‚¬μš©ν•œλ‹€.

Literal constants (λ¦¬ν„°λŸ΄ μƒμˆ˜)

  • μ •μˆ˜: 123
    • Long (λŒ€λ¬Έμž L): 123L
  • 16μ§„μˆ˜: 0x0F
  • λ°”μ΄λ„ˆλ¦¬: 0b00001011
  • Double: 123.4, 123.5e10
  • Float (f λ˜λŠ” F): 123.5f

JVMμ—μ„œμ˜ 숫자 ν‘œν˜„

JVMμ—μ„œ μˆ«μžλŠ” int, double λ“±κ³Ό 같은 primitive νƒ€μž…μœΌλ‘œ μ €μž₯λœλ‹€. Kotlin의 Nullable μ°Έμ‘° (ex, Int?)λŠ” Java의 boxed νƒ€μž… (Integer, Double, …)으둜 μ €μž₯λœλ‹€.

-> Nullable μ°Έμ‘°λŠ” 같은 μˆ«μžμ΄λ”λΌλ„ λ‹€λ₯Έ 객체가 될 수 μžˆλ‹€.

val a: Int = 100
val boxedA: Int? = a
val anotherBoxedA: Int? = a

val b: Int = 10000
val boxedB: Int? = b
val anotherBoxedB: Int? = b

println(boxedA === anotherBoxedA) // true
println(boxedB === anotherBoxedB) // false

Comments