0
0
Kotlinprogramming~15 mins

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

Choose your learning style9 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.