The standard library
Slide 49 of 85
49convThe standard library

Conversions

hive.conv is pure, so it works in a func as well as a proc, and it is the only place a number changes kind — nothing converts one implicitly.

  • ceil(v), floor(v) and round(v) turn a Float into an Int: up, down, and to the nearest with a half rounded away from zero. So ceil(-0.5) is 0, floor(-0.5) is -1 and round(-0.5) is -1.
  • itf(v) widens an Int to a Float.
  • its(v) and fts(v) write a number as a Str, the way echo does: fts(3.0) is "3".
  • sti(text) and stf(text) read a number back, and answer with a Result whose ConversionError carries the input and a message. sti takes an optional sign and decimal digits, nothing else — not " 42", 1_000, 0x1F, 1.0, or a number too big for an Int. stf takes what Go's parser does, exponents and Inf included, but no spaces and no comma for a point.
Parsing text
proc main(): void {
	if hive.conv.sti("42") is Result.Ok(n) {
		echo n + 1
	}
}
Rounding and widening
proc main(): void {
	half := hive.conv.itf(5) / 2.0   // widen first — Int and Float never mix
	echo hive.conv.round(half)
	echo hive.conv.fts(half)
	echo hive.conv.its(hive.conv.ceil(half))
}
What sti refuses
proc main(): void {
	for each text in ["+5", " 42", "1_000", "1.0"] {
		if hive.conv.sti(text) is Result.Ok(n) {
			echo "{text} -> {n}"
		} else if hive.conv.sti(text) is Result.Error(why) {
			echo "{why.input}: {why.message}"
		}
	}
	echo hive.conv.floor(-0.5)    // -1
	echo hive.conv.ceil(-0.5)     // 0
}