The standard librarySlide 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)andround(v)turn aFloatinto anInt: up, down, and to the nearest with a half rounded away from zero. Soceil(-0.5)is0,floor(-0.5)is-1andround(-0.5)is-1.itf(v)widens anIntto aFloat.its(v)andfts(v)write a number as aStr, the wayechodoes:fts(3.0)is"3".sti(text)andstf(text)read a number back, and answer with aResultwhoseConversionErrorcarries theinputand amessage.stitakes an optional sign and decimal digits, nothing else — not" 42",1_000,0x1F,1.0, or a number too big for anInt.stftakes what Go's parser does, exponents andInfincluded, 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
}
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.
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))
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.
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
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.