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"
::<lang go>package main
 
import "unicode"(
func IsNumeric(s string) bool {
"fmt"
<lang go>import "strconv"
)
 
func IsNumericisNumeric(s string) bool {
_, 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 (
"fmt"
"strconv"
"unicode"
)
import "unicode"
 
func isInt(s string) bool {
for _, c := range s {
if !unicode.IsDigit(c) {
return false
}
}
}
}
return true
}
 
func main() {
fmt.Println("Are these strings integers?")
v := "1"
if _, err := strconv.Atoi(v); err == nil {
b := false
fmt.Printf("%q looks like a number.\n", v) // // prt "1" looks like a number.
if _, err := strconv.Atoi(v); err == nil {
}
b = true
i := "one"
}
fmt.Println(isInt(i)) // prt false
fmt.Printf(" %3s -> %t\n", v, b)
i := "one"
fmt.Printf(" %3s -> %t\n", i, isInt(i))
}</lang>
 
{{out}}
<pre>
Are these strings integers?
1 -> true
one -> false
</pre>
 
=={{header|Groovy}}==
9,492

edits