Bird
Raised Fist0
Kotlinprogramming~15 mins

Int, Long, Float, Double number types in Kotlin - Deep Dive

Choose your learning style10 modes available
Overview - Int, Long, Float, Double number types
What is it?
In Kotlin, Int, Long, Float, and Double are basic number types used to store numeric values. Int and Long store whole numbers, with Long able to hold much bigger numbers than Int. Float and Double store decimal numbers, with Double offering more precision than Float. These types help the computer understand how to save and work with numbers efficiently.
Why it matters
Using the right number type helps your program use memory wisely and perform calculations correctly. Without these types, computers would waste space or give wrong answers because they wouldn't know how big or precise your numbers need to be. This matters especially in apps that handle money, measurements, or large data sets where accuracy and performance are important.
Where it fits
Before learning these types, you should understand basic variables and data types in Kotlin. After this, you can learn about arithmetic operations, type conversions, and how Kotlin handles numbers in expressions and functions.
Mental Model
Core Idea
Number types in Kotlin define how much space a number takes and how precise it can be, guiding the computer on how to store and calculate with that number.
Think of it like...
Think of number types like different sizes of containers: Int is a medium box for whole items, Long is a big box for many whole items, Float is a small jar for rough liquids, and Double is a large jar for precise liquids.
┌─────────────┬───────────────┬───────────────┐
│ Type        │ Stores        │ Size (bits)   │
├─────────────┼───────────────┼───────────────┤
│ Int         │ Whole numbers │ 32            │
│ Long        │ Whole numbers │ 64            │
│ Float       │ Decimal nums  │ 32            │
│ Double      │ Decimal nums  │ 64            │
└─────────────┴───────────────┴───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Int type basics
🤔
Concept: Int stores whole numbers using 32 bits of memory.
In Kotlin, Int is used to store whole numbers without decimals. It can hold values from -2,147,483,648 to 2,147,483,647. For example: val age: Int = 25 val year: Int = 2024 These numbers fit comfortably in 32 bits, which is 4 bytes of memory.
Result
You can store and use whole numbers within the Int range efficiently.
Understanding Int helps you store common whole numbers efficiently without wasting memory.
2
FoundationIntroducing Long for bigger whole numbers
🤔
Concept: Long stores larger whole numbers using 64 bits.
When numbers are too big for Int, Kotlin uses Long. It can hold values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Example: val distance: Long = 5000000000L Note the 'L' suffix to tell Kotlin this is a Long number.
Result
You can handle very large whole numbers safely without overflow.
Knowing Long prevents errors when working with numbers bigger than Int can hold.
3
IntermediateUsing Float for decimal numbers
🤔Before reading on: do you think Float stores decimal numbers with perfect precision or some approximation? Commit to your answer.
Concept: Float stores decimal numbers but with limited precision using 32 bits.
Float is used for decimal numbers but it cannot represent all decimals exactly. It uses 32 bits and can hold about 6-7 digits of precision. Example: val price: Float = 12.99F The 'F' suffix tells Kotlin this is a Float.
Result
You can store decimal numbers but some small rounding errors may happen.
Understanding Float's limited precision helps avoid surprises in calculations needing exact decimals.
4
IntermediateDouble for precise decimal numbers
🤔Before reading on: do you think Double is twice as precise as Float or just a bit better? Commit to your answer.
Concept: Double stores decimal numbers with higher precision using 64 bits.
Double is the default decimal type in Kotlin. It uses 64 bits and can hold about 15-16 digits of precision. Example: val pi: Double = 3.141592653589793 Double is better for scientific or financial calculations needing accuracy.
Result
You get more precise decimal numbers with less rounding error.
Knowing Double's precision helps choose the right type for accurate decimal math.
5
IntermediateType suffixes and literals in Kotlin
🤔
Concept: Kotlin uses suffixes like L and F to mark Long and Float literals explicitly.
By default, numbers with decimals are Double, and whole numbers are Int. To specify Long or Float, you add suffixes: val bigNumber = 1234567890123L // Long val smallDecimal = 1.23F // Float Without suffixes, Kotlin assumes Int or Double.
Result
You can control number types precisely when writing code.
Understanding suffixes prevents type errors and ensures correct number storage.
6
AdvancedType conversion and overflow risks
🤔Before reading on: do you think Kotlin automatically converts Int to Long in all cases? Commit to your answer.
Concept: Kotlin requires explicit conversion between number types and warns about overflow risks.
Kotlin does not automatically convert between Int, Long, Float, and Double. You must convert explicitly: val i: Int = 100 val l: Long = i.toLong() Also, if a number exceeds the type's limit, it overflows and wraps around silently: val maxInt = Int.MAX_VALUE val overflow = maxInt + 1 // wraps to Int.MIN_VALUE
Result
You avoid bugs by converting types explicitly and watching for overflow.
Knowing Kotlin's strict conversions and overflow behavior helps write safer numeric code.
7
ExpertFloating-point precision and binary storage
🤔Before reading on: do you think Float and Double store decimal numbers exactly as typed? Commit to your answer.
Concept: Float and Double store decimal numbers in binary, causing some decimals to be approximated.
Computers store Float and Double in binary format, which cannot represent many decimal fractions exactly. For example, 0.1 cannot be stored precisely, leading to tiny errors in calculations: val a = 0.1 + 0.2 println(a == 0.3) // prints false This is normal and expected in floating-point math.
Result
You understand why some decimal calculations seem 'off' and how to handle them.
Understanding binary floating-point storage prevents confusion and guides use of rounding or BigDecimal for exact decimals.
Under the Hood
Int and Long store numbers as binary integers using fixed bits (32 or 64). Float and Double use IEEE 754 standard for floating-point numbers, splitting bits into sign, exponent, and mantissa to represent a wide range of decimal values approximately. Kotlin's compiler and runtime enforce type sizes and conversions, and the JVM or native platform handles actual memory layout and arithmetic.
Why designed this way?
These types follow hardware and JVM standards to balance memory use, speed, and precision. Int and Long map directly to CPU integer registers for fast math. Float and Double follow IEEE 754 for compatibility and wide use in scientific computing. Kotlin's explicit conversions avoid hidden bugs common in languages with implicit casts.
┌───────────────┐       ┌───────────────┐
│   Int (32b)   │       │   Long (64b)  │
│  [binary int] │       │  [binary int] │
└──────┬────────┘       └──────┬────────┘
       │                       │
       │                       │
       ▼                       ▼
┌───────────────────────────────┐
│       JVM / CPU registers      │
└───────────────────────────────┘
       ▲                       ▲
       │                       │
┌──────┴────────┐       ┌──────┴────────┐
│ Float (32b)   │       │ Double (64b)  │
│ [sign|exp|man]│       │ [sign|exp|man]│
└───────────────┘       └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think Kotlin automatically converts Int to Long when needed? Commit to yes or no.
Common Belief:Kotlin automatically converts Int to Long when you assign or use them together.
Tap to reveal reality
Reality:Kotlin requires explicit conversion using toLong() to convert Int to Long; it does not do this automatically.
Why it matters:Assuming automatic conversion leads to compilation errors or unexpected bugs when mixing number types.
Quick: Do you think Float and Double store decimal numbers exactly as typed? Commit to yes or no.
Common Belief:Float and Double store decimal numbers exactly without any rounding errors.
Tap to reveal reality
Reality:Float and Double store decimal numbers approximately in binary, causing small rounding errors.
Why it matters:Ignoring this causes confusion in calculations, especially in financial or scientific apps needing exact decimals.
Quick: Do you think adding 1 to Int.MAX_VALUE causes an error or exception? Commit to error or wrap-around.
Common Belief:Adding 1 to Int.MAX_VALUE causes an error or exception in Kotlin.
Tap to reveal reality
Reality:It silently wraps around to Int.MIN_VALUE due to overflow.
Why it matters:Not knowing this can cause subtle bugs and incorrect results in numeric computations.
Quick: Do you think Double is just a bigger Float with no other differences? Commit to yes or no.
Common Belief:Double is just a bigger Float with the same behavior and precision.
Tap to reveal reality
Reality:Double has more bits for exponent and mantissa, giving it much higher precision and range than Float.
Why it matters:Using Float when Double is needed can cause loss of important precision.
Expert Zone
1
Kotlin's number types map closely to JVM primitives, but Kotlin also supports nullable boxed types which behave differently in performance and memory.
2
Floating-point arithmetic follows IEEE 754 rules, including special values like NaN and infinity, which can affect comparisons and calculations.
3
Explicit conversions prevent accidental data loss but require careful handling in generic code or APIs expecting different numeric types.
When NOT to use
Avoid Float and Double for exact decimal calculations like money; use BigDecimal instead. For very large integers beyond Long, use BigInteger. When performance is critical and numbers fit in Int, prefer Int over Long to save memory.
Production Patterns
In real apps, Int is used for counts and small numbers, Long for timestamps or large IDs, Float for graphics or sensor data where precision is less critical, and Double for scientific or financial calculations. Explicit conversions and overflow checks are common in robust systems.
Connections
Binary Number System
builds-on
Understanding how numbers are stored in binary helps explain why Int and Long have fixed ranges and why Float and Double approximate decimals.
Data Types and Memory Management
builds-on
Knowing how data types affect memory use guides choosing the right number type for efficient programs.
Financial Accounting
opposite
Financial accounting requires exact decimal precision, highlighting why floating-point types are unsuitable for money calculations.
Common Pitfalls
#1Using Int for numbers larger than its max value causes silent overflow.
Wrong approach:val bigNumber: Int = 3000000000
Correct approach:val bigNumber: Long = 3000000000L
Root cause:Not knowing Int's maximum range and forgetting to use Long for bigger numbers.
#2Assuming Float stores decimal numbers exactly leads to rounding errors.
Wrong approach:val price: Float = 0.1F + 0.2F println(price == 0.3F) // expects true
Correct approach:val price: Double = 0.1 + 0.2 println(price == 0.3) // still false, handle with rounding
Root cause:Misunderstanding floating-point binary representation and precision limits.
#3Mixing number types without explicit conversion causes compile errors.
Wrong approach:val i: Int = 10 val l: Long = i + 5L // error
Correct approach:val i: Int = 10 val l: Long = i.toLong() + 5L
Root cause:Not realizing Kotlin requires explicit conversions between numeric types.
Key Takeaways
Int and Long store whole numbers with 32 and 64 bits respectively, defining their size and range.
Float and Double store decimal numbers approximately using 32 and 64 bits, with Double offering higher precision.
Kotlin requires explicit conversions between number types to avoid hidden bugs and data loss.
Floating-point types cannot represent all decimals exactly due to binary storage, causing small rounding errors.
Choosing the right number type balances memory use, precision, and performance for your program's needs.

Practice

(1/5)
1. Which Kotlin number type should you use to store a whole number like 42?
easy
A. Float
B. Double
C. Int
D. Long

Solution

  1. Step 1: Understand the number type categories

    Int is used for normal whole numbers without decimals.
  2. Step 2: Match the number 42 to the type

    42 is a whole number and fits in Int range.
  3. Final Answer:

    Int -> Option C
  4. Quick Check:

    Whole number 42 = Int [OK]
Hint: Whole numbers without decimals use Int by default [OK]
Common Mistakes:
  • Choosing Float or Double for whole numbers
  • Using Long unnecessarily for small numbers
2. Which of the following is the correct way to declare a Float variable with value 3.14 in Kotlin?
easy
A. val pi: Float = 3.14
B. val pi: Float = 3.14Ff
C. val pi: Float = 3.14d
D. val pi: Float = 3.14f

Solution

  1. Step 1: Recall Kotlin Float literal syntax

    Float literals require an 'f' or 'F' suffix to distinguish from Double.
  2. Step 2: Check each option

    val pi: Float = 3.14f uses '3.14f' which is correct. val pi: Float = 3.14 misses the suffix. val pi: Float = 3.14Ff has invalid suffix 'Ff'. val pi: Float = 3.14d uses 'd' which is for Double.
  3. Final Answer:

    val pi: Float = 3.14f -> Option D
  4. Quick Check:

    Float literals end with 'f' [OK]
Hint: Add 'f' suffix to decimal for Float type [OK]
Common Mistakes:
  • Omitting 'f' suffix for Float literals
  • Using 'd' suffix which is for Double
  • Using invalid suffixes like 'Ff'
3. What will be the output of this Kotlin code?
val a: Int = 100000
val b: Long = 10000000000L
val c: Float = 3.14f
val d: Double = 3.1415926535
println("$a $b $c $d")
medium
A. 100000 10000000000 3.1400001 3.1415926535
B. 100000 10000000000 3.14 3.1415926535
C. 100000 10000000000 3.14f 3.1415926535
D. 100000 10000000000 3.14 3.1415927

Solution

  1. Step 1: Understand variable types and precision

    a is Int (100000), b is Long (10000000000L), c is Float (3.14f), d is Double (3.1415926535).
  2. Step 2: Check printed values and precision

    Float prints as 3.1400001 due to precision limits, Double prints full precision (3.1415926535). So output matches 100000 10000000000 3.1400001 3.1415926535.
  3. Final Answer:

    100000 10000000000 3.1400001 3.1415926535 -> Option A
  4. Quick Check:

    Float prints with slight precision difference [OK]
Hint: Float prints decimals with limited precision [OK]
Common Mistakes:
  • Thinking Float prints exactly 3.14
  • Confusing Float and Double precision
  • Misreading Long large number formatting
4. Identify the error in this Kotlin code snippet:
val bigNumber: Long = 12345678901234567890
val smallNumber: Int = 2147483648
medium
A. Both numbers are too large for their types
B. Only bigNumber is too large for Long
C. No errors, code is correct
D. Only smallNumber is too large for Int

Solution

  1. Step 1: Check Long value range

    Long can hold values up to 9,223,372,036,854,775,807. The bigNumber literal exceeds this, so it causes an error.
  2. Step 2: Check Int value range

    Int max is 2,147,483,647. The smallNumber is 2,147,483,648 which is 1 more than max, so it causes an error.
  3. Step 3: Analyze the code

    Both literals are too large for their types, causing compile errors.
  4. Final Answer:

    Both numbers are too large for their types -> Option A
  5. Quick Check:

    Int max 2147483647, Long max 9223372036854775807; both exceeded [OK]
Hint: Check max values: Int max 2,147,483,647; Long max 9,223,372,036,854,775,807 [OK]
Common Mistakes:
  • Ignoring suffix 'L' for Long literals
  • Assuming Long can hold any big number
  • Not checking Int max value
5. You want to store the population of a country which is about 1.4 billion people. Which Kotlin type is best and why?

Options:
A) Long because it can store very large whole numbers
B) Int because it stores whole numbers
C) Float because it stores decimal numbers
D) Double because it stores decimal numbers with more precision
hard
A. Int because it stores whole numbers
B. Long because it can store very large whole numbers
C. Float because it stores decimal numbers
D. Double because it stores decimal numbers with more precision

Solution

  1. Step 1: Understand the population size and type limits

    Population is about 1.4 billion (1,400,000,000). Int max is 2,147,483,647, so Int can hold it.
  2. Step 2: Consider best practice for large numbers

    Though Int can hold 1.4 billion, Long is safer for very large whole numbers and future growth.
  3. Step 3: Decide on the best type

    Long is best because it can store very large whole numbers beyond Int range.
  4. Final Answer:

    Long because it can store very large whole numbers -> Option B
  5. Quick Check:

    Long preferred for large integers like population [OK]
Hint: Use Long for very large whole numbers like population [OK]
Common Mistakes:
  • Choosing Int without considering future growth
  • Using Float or Double for whole numbers unnecessarily
  • Ignoring future growth beyond Int range
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard