0
0
KotlinConceptBeginner · 3 min read

What is Double in Kotlin: Explanation and Examples

Double in Kotlin is a data type used to store decimal numbers with double precision (64 bits). It is useful when you need to represent numbers with fractions or very large/small values accurately.
⚙️

How It Works

Think of Double as a way to hold numbers that have a decimal point, like 3.14 or -0.001. It uses 64 bits of memory to store these numbers, which means it can represent very large or very small decimal values with good accuracy.

Imagine measuring the length of a table in meters. If you want to say it's exactly 2 meters, you can use a whole number. But if you want to say it's 2.35 meters, you need a type that can hold decimals. That's where Double helps in Kotlin.

💻

Example

This example shows how to declare and use a Double variable in Kotlin.

kotlin
fun main() {
    val pi: Double = 3.14159
    val radius = 5.0
    val area = pi * radius * radius
    println("Area of circle: $area")
}
Output
Area of circle: 78.53975
🎯

When to Use

Use Double when you need to work with decimal numbers that require precision, such as measurements, scientific calculations, or financial data where fractions matter.

For example, calculating areas, distances, or currency values often needs Double because whole numbers (like Int) can't represent fractions.

Key Points

  • Double stores decimal numbers with 64-bit precision.
  • It is suitable for numbers with fractions or very large/small values.
  • Use it when accuracy with decimals is important.
  • It is a primitive type in Kotlin and interoperates well with Java.

Key Takeaways

Double holds decimal numbers with high precision in Kotlin.
Use Double for calculations involving fractions or precise measurements.
It uses 64 bits of memory to store values, allowing large and small numbers.
For whole numbers without decimals, use Int instead.