Floating-point types
- Kotlin course
- Beginner
- Lesson 14/116
- 4 min
Learn Double and Float types.
Floating-point types
In Kotlin, floating-point numbers come in two types: Double (64 bit, double precision) and Float (32 bit, single precision). Double is the default floating-point type; for example, writing val pi = 3.14 infers Double.
To use Float, you add the f suffix: val g = 9.81f. Double is preferred where precision matters (scientific calculations, money).
val pi: Double = 3.14159 // 64 bit
val g: Float = 9.81f // 32 bit (f suffix)Practice Compute with Double
Write a fun main(). Declare val pi: Double = 3.14 and val r: Double = 2.0. Print the circle area with println(pi * r * r).
Sample solution
fun main() {
val pi: Double = 3.14
val r: Double = 2.0
println(pi * r * r)
}Expected output
12.56
Precision warning
Floating-point numbers always hold approximate values; some decimals cannot be represented exactly in binary. For example, 0.1 + 0.2 is not exactly 0.3.
For precise calculations like money, BigDecimal is safer. Float is less precise than Double, so it is rarely preferred.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Float suffix
val f = 3.14____
val f = 3.14f
Explanation: Float literals are written with the f suffix.
2 Which is the default floating-point type?
- Float
- Double Correct answer
- Int
- Long
Explanation: Double is the default floating-point type.
3 Floating-point types: match the terms
| Term | Meaning |
|---|---|
Double |
64 bit |
Float |
32 bit |
Int |
32-bit integer |
Long |
64-bit integer |