Determine if a string is numeric: Difference between revisions
→{{header|Go}}: Cleaned up this entry as the first example was old code which no longer compiled.
(→{{header|Go}}: Cleaned up this entry as the first example was old code which no longer compiled.) |
|||
Line 1,778:
=={{header|Go}}==
This uses a library function to meet the task's requirements:
<lang go>import "strconv"▼
func IsNumeric(s string) bool {▼
"fmt"
)
_, err := strconv.ParseFloat(s, 64)
return err == nil
func main() {
fmt.Println("Are these strings numeric?")
strings := []string{"1", "3.14", "-100", "1e2", "NaN", "rose"}
for _, s := range strings {
fmt.Printf(" %4s -> %t\n", s, isNumeric(s))
}
}</lang>
{{out}}
▲::<lang go>package main
<pre>
Are these strings numeric?
1 -> true
3.14 -> true
-100 -> true
1e2 -> true
NaN -> true
rose -> false
</pre>
This uses both a library function and a custom one but only checks for integerness:
<lang go>package main
import (
"unicode"
)
▲import "unicode"
func isInt(s string) bool {
}
}
▲ }
}
func main() {
fmt.Println("Are these strings integers?")
if _, err := strconv.Atoi(v); err == nil {▼
b := false
b = true
i := "one"▼
}
fmt.Printf(" %3s -> %t\n", v, b)
fmt.Printf(" %3s -> %t\n", i, isInt(i))
}</lang>
{{out}}
<pre>
Are these strings integers?
1 -> true
one -> false
</pre>
=={{header|Groovy}}==
|