Test if a CString is Numeric

newstandard used Ask the Experts™
I want to create an IsNumeric(CString) function. I have some code that seems to work, but since I am new to c++ I want to make sure it is the best way to do this.

BOOL myClass::isNumeric(CString text)
      CString temp;
      temp.Format("%d", _ttoi(text));
      if (temp.GetLength()==text.GetLength()) return TRUE;
      else return FALSE;
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2012

I'd use

#include <stdlib.h>

BOOL myClass::isNumeric(CString text)
   long l;
   char* pcCnvEnd;

   l = strtol ( ( LPCTSTR) text, &pcCnvEnd, 10);

   if ( *pcCnvEnd) { // conversion stopped at sth. that was not the trailing NULL byte

        return FALSE;

    return TRUE;
Do you need to deal with floating point numbers?

This code will work for whole numbers, negative numbers and decimals in the form 1.23 :

BOOL isNumeric(const CString & text)
   BOOL bNumeric = TRUE;
   LPCSTR szText = text; // Saves CString's array access overheads

   while (bNumeric && *szText)
      if (!isdigit(*szText) && *szText != '-' && *szText != '.')
         bNumeric = FALSE;

   return bNumeric;

Note that the string is passed in by reference, which saves the overhead of creating a new CString and calling it's copy constructor.

Hope this helps

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial