Int, Double, Float, Long
Int, Double, Float, and Long are different-sized number boxes: small whole numbers, big whole numbers, and numbers with decimals. You pick the box that fits the number you have.
In this page:
Syntax
val i: Int = 42
val l: Long = 42L
val d: Double = 3.14
val f: Float = 3.14f
Int, Double, Float, Long
Int is a 32-bit whole number, Long extends that to 64 bits (with an L suffix on literals), and Double/Float represent 64-bit and 32-bit floating-point numbers respectively (with an f suffix for Float literals).
Double is the default type for decimal literals unless a Float is explicitly requested. Choosing the right numeric type matters for both precision and memory usage.
Note:
Without an explicit type annotation or suffix, a decimal literal like
3.14 is inferred as Double, not Float.Example: Int, Double, Float, Long
object Main extends App {
val age: Int = 30
val population: Long = 8000000000L
val price: Double = 19.99
val temperature: Float = 36.6f
println(s"$age $population $price $temperature")
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Storing a big number like
val big: Long = 8000000000with noL, causing aninteger number too largeerror. - Writing
val f: Float = 36.6withoutf, causing a type error because36.6is aDouble. - Dividing two
Intvalues such as7 / 2and expecting3.5, when it gives3.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: