Filter löschen
Filter löschen

How to check if a string contains only numbers?

241 Ansichten (letzte 30 Tage)
Rahul Pillai
Rahul Pillai am 14 Dez. 2017
Kommentiert: YT am 15 Dez. 2017
Is there any expression for this ? For example :
-100 should return 1
a100b should return 0
0.1256 should return 1 and so on

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 14 Dez. 2017
The easiest way is to check if str2double() returns nan. Otherwise you need to parse the string and there are a number of odd cases to account for in scientific notation.
Note: if you do use str2double() you should give some consideration as to what result you want for complex numbers, whether those are to be treated as numeric or as invalid because of the 'i' or 'j' present.
  4 Kommentare
Stephen23
Stephen23 am 15 Dez. 2017
"why would it be easier than isnumeric()?"
Because isnumeric tests if the type is numeric. The question specifically states the input is string/char.
YT
YT am 15 Dez. 2017
@replies, thanks for clarifying. Somehow I didn't read the title well enough. I'll remove my answer.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Data Type Identification finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by