05Operators
Converting between kinds
Turn a value of one kind into another with ပြောင်းလဲသော ရလဒ်.
Sometimes a value comes in one kind but the program needs another: an integer count to divide as a decimal, a decimal score to round down to a whole number, or a character's Unicode number. Converting gives the value in the new kind.
Expected output
၃၇.၀
၉
၆၅
B
၁
The phrase reads "the result of changing x into kind":
| Zaka | Reads as |
|---|---|
အသက် | "age" — the value to convert |
ကို | (object) |
ဒဿမကိန်း | the target kind |
အဖြစ် | "as", "into" |
ပြောင်းလဲသော ရလဒ် | "the changed result" |
Converting can lose data
Each conversion has to be written out, because it can change the value:
- Decimal to integer drops the fraction, toward zero:
၉.၇၅becomes၉,-၂.၇becomes-၂. - A number too big for a smaller kind wraps around: 300 as
လက္ခဏာမဲ့ ၈ ဘစ် ကိန်းပြည့်is 44. - A negative number as an unsigned kind wraps too:
-၁becomes 255.
Expected output
-၂
၄၄
၂၅၅
Some conversions make no sense and are refused. A number cannot become true or false:
Expected error
error[ZK0408]: cannot convert isize to bool
Automatic conversion
When nothing can be lost, Zaka converts on its own. A smaller kind goes into a bigger
one: an ၈ ဘစ် ကိန်းပြည့် into a ကိန်းပြည့်, or into a decimal
number. These are called widening conversions.
Expected output
၁၀
၁၀.၀
A plain ကိန်းပြည့် does not go into a decimal on its own. It has 64 bits, and a
decimal cannot hold all 64-bit integers without loss:
Expected error
error[ZK0401]: expected f64, found isize
Write the conversion out. Here is an average that keeps its fraction:
Expected output
၂
၂.၅
The parentheses let a conversion phrase sit inside a / sum. The next page explains
the reason.
Hands on
- Print the Unicode number of
'က'. - Print the character whose number is 4160.
Next: Grouping and order.