Careeroza
Numbers
Integer Types and Their Limits
Example
Each integer type has a minimum and maximum value. Whole numbers default to Int; add L for Long.
fun main() {
println("Byte: ${Byte.MIN_VALUE} to ${Byte.MAX_VALUE}")
println("Short: ${Short.MIN_VALUE} to ${Short.MAX_VALUE}")
println("Int: ${Int.MIN_VALUE} to ${Int.MAX_VALUE}")
println("Long: ${Long.MIN_VALUE} to ${Long.MAX_VALUE}")
val views = 3_000_000_000 // too big for Int, so inferred as Long
println(views::class.simpleName)
}Output
Byte: -128 to 127 Short: -32768 to 32767 Int: -2147483648 to 2147483647 Long: -9223372036854775808 to 9223372036854775807 Long
Overflow
Example
Going past Int.MAX_VALUE silently wraps around to a negative number. Use Long for big values such as amounts in paise, view counts or timestamps.
fun main() {
val max = Int.MAX_VALUE
println(max + 1) // wraps around!
println(max.toLong() + 1) // correct with Long
}Output
-2147483648 2147483648
Floating-Point Numbers
Example
Decimal numbers default to Double (about 15–16 digits). Float needs an f suffix and keeps about 6–7 digits.
fun main() {
val d = 10.0 / 3
val f = 10f / 3
println(d)
println(f)
println(0.1 + 0.2) // binary floating point is not exact
println(10 / 3) // Int / Int = Int (decimals dropped)
println(10 / 3.0) // one Double makes the result Double
}Output
3.3333333333333335 3.3333333 0.30000000000000004 3 3.3333333333333335
Tip: Never use Double for money in real apps: 0.1 + 0.2 is not exactly 0.3. Store amounts as Long paise (₹ 12.50 = 1250) or use BigDecimal. Payment apps like PhonePe and Paytm do exactly this.
Literals
Example
Underscores make big numbers readable. Hex and binary literals are also supported.
fun main() {
val oneCrore = 1_00_00_000
val color = 0xFF6200EE // hex (Android colors), a Long here
val flags = 0b1010 // binary
println(oneCrore)
println(color)
println(flags)
println(1.5e3) // scientific notation
}Output
10000000 4284612846 10 1500.0