Jump to content

Determine if a string is numeric: Difference between revisions

Another example inspired by Kotlin code
(The previous example was not a complete and compilable example.)
(Another example inspired by Kotlin code)
Line 2,142:
 
<syntaxhighlight lang="java">
 
class Main
{
Line 2,175 ⟶ 2,176:
For '2a5': false
For '-2.1e5': true
</pre>
 
Another example inspired by the Kotlin example. Fantom does not have an enhanced for-loop (foreach) loop, but instead uses Closures as the primary mechanism of iteration.
 
<syntaxhighlight lang="java">
/* gary chike 08/27/2023 */
 
class Main {
 
static Void main() {
 
inputs := ["152\n", "-3.141", "Foo123", "-0", "456bar", "1.0E10"]
 
inputs.each |Str input| { echo("$input.trim \tis " + (isNumeric(input) ? "numeric" : "not numeric"))}
 
static Bool isNumeric(Str input) {
try {
input.toFloat
return true
}
catch(Err e) {
return false
}
}
}
</syntaxhighlight>
{{out}}
<pre>
152 is numeric
-3.141 is numeric
Foo123 is not numeric
-0 is numeric
456bar is not numeric
1.0E10 is numeric
</pre>
 
62

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.