Skip to content
Kavachकवच

Strings: Strings to numbers

● Beginner3 min

Int(text) reads a whole string as a number, and can fail; std.text finds numbers inside other text.

fn main() {
    const n: Int = 7
    const f = Float(n) / 2.0
    print(f)
    const typed = "42"
    const parsed = Int(typed) catch _ => 0
    print(parsed + 1)
    const answer = "forty-two"
    const bad = Int(answer) catch _ => -1
    print(bad)
    print(Int("2") + Int("2"))
}

The program ran and printed:

kavach run convert.kav

3.543-14
convert.kav: Kavach code, then what running it prints

To find numbers in the middle of text, such as an order number in a message, use std.text:

use std.text

fn main() {
    print(text.find_int("Order #4521 shipped") ?? 0)
    print(text.find_ints("rooms 12, 14 and 15"))
    print(text.find_float("pi is about 3.14!") ?? 0.0)
    print(text.find_int("no number here") ?? -1)
}

The program ran and printed:

kavach run find.kav

4521[12, 14, 15]3.14-1
find.kav: Kavach code, then what running it prints