How to check if a string contains only numbers?
40 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Rahul Pillai
am 14 Dez. 2017
Kommentiert: Steven Lord
am 16 Apr. 2025
Is there any expression for this ? For example :
-100 should return 1
a100b should return 0
0.1256 should return 1 and so on
0 Kommentare
Akzeptierte Antwort
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.
7 Kommentare
Walter Roberson
am 16 Apr. 2025
Hah, yes,
nan == nan
nan >= nan
nan < nan
all returning false is an oddity of floating point numbers. Oddly enough,
nan ~= nan
returns true, so an alternate way to test for nan is
x ~= x
Steven Lord
am 16 Apr. 2025
I would not describe the behavior of the relational operators with one of the inputs being NaN an "oddity". It's how NaN is defined to work in the IEEE 754 specification, as summarized on the NaN Wikipedia page. In IEEE 754-2019 it's section 5.11. A short excerpt:
"Four mutually exclusive relations are possible: less than, equal, greater than, and unordered; unordered arises when at least one operand is a NaN. Every NaN shall compare unordered with everything, including itself."
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Data Type Conversion 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!