by 2h · 3y ago · 0 comments
function NUMBER( res) {
return (tryParse1("-", res) || 1) &&
(tryParse1("0", res) || tryParse1("123456789", res) && (tryParseDigits(res)||1)) &&
(tryParse1(".", res) ? tryParseDigits(res) : 1) &&
(tryParse1("eE", res) ? (tryParse1("-+",res)||1) && tryParseDigits(res) : 1) &&
asm("number") && asm(res[0])
}
why put yourself through this, when you can just do something like this instead: package parse
import "strconv"
func parse_float(s string) (float64, error) {
return strconv.ParseFloat(s, 64)
}
func parse_int(s string) (int64, error) {
return strconv.ParseInt(s, 10, 64)
}Funnily the actual Go JSON decoder code ends up doing something similar during scanning:
https://github.com/golang/go/blob/master/src/encoding/json/d...
bash> awk -v v="80.1%" 'BEGIN{print v+0.1}'
80.2
gawk has `strtonum`. But yes, parsing in awk generally looks like a pain. With plain positive/negative ints though, not so hard: echo "123456" | awk '{
if ($0 ~ /^-?[0-9]+$/) {
num = 0
sign = 1
start = 1
if (substr($0, 1, 1) == "-") {
sign = -1
start = 2
}
for (i = start; i <= length($0); i++) {
digit = substr($0, i, 1)
num = num * 10 + digit
}
num = sign * num
print "The integer is:", num
} else {
print "Invalid input string:", $0
}
}'