Whole Numbers and Decimals
Asha ran 12 laps of the 400-metre track. Is that 4 kilometres or 4.8? In Scala, both answers are one character apart, and the difference comes entirely from which number types are involved.
The rule
Int for counting, Double for measuring; whole divided by whole stays whole.
Scala has six number types. Four of them cover almost everything:
| Type | Holds | Size | Literal |
|---|---|---|---|
Int |
whole numbers up to about ±2.1 billion | 32 bits | 12 |
Long |
much larger whole numbers | 64 bits | 3_000_000_000L |
Double |
decimals, about 15 significant digits | 64 bits | 4.8 |
Float |
decimals, about 7 significant digits | 32 bits | 4.8f |
Byte (8 bits) and Short (16 bits) also exist, mostly for files and hardware. A whole-number literal is an Int unless you add L; a decimal literal is a Double unless you add f. Underscores can group digits, so 1_530 is the same as 1530.
val laps = 12 // Int
val metres = laps * 400 // Int: 4800
val km = metres / 1000 // Int: 4, the .8 is thrown away
val kmExact = metres / 1000.0 // Double: 4.8When both sides of / are whole numbers, the result is whole and the remainder is dropped. If either side is a Double, the result is a Double.
Two more edges to know:
- Overflow wraps silently.
Int.MaxValue + 1is-2147483648, with no error. UseLongfor counts that might pass two billion. Writing3_000_000_000without theLis rejected as "number too large". - Decimals are approximate.
12 * 0.4gives4.800000000000001, because 0.4 has no exact binary form. That is fine for distances; for money, useBigDecimal.
The shortcut
Before reading any arithmetic, tag each number I or D. Whole numbers and Int names get I; decimals get D. Any operation with a D makes a D. I with I stays I, and I / I drops the remainder.
Tag the inputs
lapsis 12, tagged I. The track length 400 is also I.
The trap is a total that looks plausible but has been quietly rounded down, like the 4 above. The tags catch it before the club sees the wrong number.
Drills
Answer fast — trust the rule.
What is 4800 / 1000 in Scala?
Which literal is a Long?
What does Int.MaxValue + 1 produce?
What is the type of 12 * 0.4?
A member's run took 1530 seconds. Which expression gives the whole minutes?
Remember
IntandLongcount,DoubleandFloatmeasure; plain literals areIntorDouble.- Tag each number I or D: any D makes a D, and I / I drops the remainder.
- Traps: silent overflow past about 2.1 billion, and decimals that are only approximate.
