Determine if a string is numeric: Difference between revisions

added Emacs ELisp code for solution
(added C translation to C++)
(added Emacs ELisp code for solution)
Line 2,017:
<pre>
["123", "-12.3", "-12e5", "+123"]
</pre>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">
(defun string-valid-number-p (str)
"Test if STR is a numeric string.
Eliminate strings with commas in them because ELips numbers do
not contain commas. Then check if remaining strings would be
valid ELisp numbers if the quotation marks were removed."
(and
;; no comma in string, because ELisp numbers do not have commas
;; we need to eliminate any string with a comma, because the
;; numberp function below will not weed out commas
(not (string-match-p "," str))
;; no errors from numberp function testing if a number
(ignore-errors (numberp (read str)))))
 
 
</syntaxhighlight>
{{out}}
 
<pre>
Test for valid strings:
3 - t
0 - t
-0 - t
2. - t
1000 - t
-4 - t
-5. - t
6.2 - t
-8.45 - t
+15e2 - t
-15e2 - t
#b101100 - t
#o54 - t
#x2c - t
1500.0 - t
#24r1k - t
3 - t
 
 
Test for invalid strings:
3cat - nil
1,000 - nil
5.6.7 - nil
cat3 - nil
def - nil
zero - nil
</pre>
 
33

edits