diff options
author | siddharth <s@ricketyspace.net> | 2022-01-17 18:20:29 -0500 |
---|---|---|
committer | siddharth <s@ricketyspace.net> | 2022-01-17 18:20:29 -0500 |
commit | 78ceded6e90699a5da5297d2a6cf908ad9bf6c4c (patch) | |
tree | 5927450ba38c81625223ea9e44f496d1d42d5a52 /lib/str.go | |
parent | 4e9fe3548d49c3f139fcf43c05365e4718e098d1 (diff) |
lib: add StrToNum
Diffstat (limited to 'lib/str.go')
-rw-r--r-- | lib/str.go | 28 |
1 files changed, 28 insertions, 0 deletions
@@ -153,3 +153,31 @@ func StrHas(s, n string) bool { } return false } + +// Converts a string to an integer. +func StrToNum(s string) (int, error) { + var negative bool + var n int + + if len(s) < 1 { + return 0, CPError{"invalid number"} + } + if s[0] == '-' { + negative = true + s = s[1:] + } + u := 1 + for i := len(s) - 1; i >= 0; i-- { + b := s[i] + if b >= '0' && b <= '9' { + n += int(b-48) * u + u *= 10 + } else { + return 0, CPError{"invalid number"} + } + } + if negative { + n *= -1 + } + return n, nil +} |