View source code
Display the source code in std/string.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.string.isNumeric

Takes a string s and determines if it represents a number. This function also takes an optional parameter, bAllowSep, which will accept the separator characters ',' and _ within the string. But these characters should be stripped from the string before using any of the conversion functions like to!int(), to!float(), and etc else an error will occur.

bool isNumeric(S) (
  S s,
  bool bAllowSep = false
)
if (isSomeString!S || isRandomAccessRange!S && hasSlicing!S && isSomeChar!(ElementType!S) && !isInfinite!S);

Also please note, that no spaces are allowed within the string anywhere whether it's a leading, trailing, or embedded space(s), thus they too must be stripped from the string before using this function, or any of the conversion functions.

Parameters

NameDescription
s the string or random access range to check
bAllowSep accept separator characters or not

Returns

bool

Example

Integer Whole Number: (byte, ubyte, short, ushort, int, uint, long, and ulong) ['+'|'-']digit(s)[U|L|UL]

assert(isNumeric("123"));
assert(isNumeric("123UL"));
assert(isNumeric("123L"));
assert(isNumeric("+123U"));
assert(isNumeric("-123L"));

Example

Floating-Point Number: (float, double, real, ifloat, idouble, and ireal) ['+'|'-']digit(s)[.][digit(s)][[e-|e+]digit(s)][i|f|L|Li|fi]] or [nan|nani|inf|-inf]

assert(isNumeric("+123"));
assert(isNumeric("-123.01"));
assert(isNumeric("123.3e-10f"));
assert(isNumeric("123.3e-10fi"));
assert(isNumeric("123.3e-10L"));

assert(isNumeric("nan"));
assert(isNumeric("nani"));
assert(isNumeric("-inf"));

Example

Floating-Point Number: (cfloat, cdouble, and creal) ['+'|'-']digit(s)[.][digit(s)][[e-|e+]digit(s)][+] [digit(s)[.][digit(s)][[e-|e+]digit(s)][i|f|L|Li|fi]] or [nan|nani|nan+nani|inf|-inf]

assert(isNumeric("-123e-1+456.9e-10Li"));
assert(isNumeric("+123e+10+456i"));
assert(isNumeric("123+456"));

Example

isNumeric works with CTFE

enum a = isNumeric("123.00E-5+1234.45E-12Li");
enum b = isNumeric("12345xxxx890");

static assert( a);
static assert(!b);

Authors

Walter Bright, Andrei Alexandrescu, Jonathan M Davis, and David L. 'SpottedTiger' Davis

License

Boost License 1.0.