简体   繁体   中英

How to check if entry is number including float numbers

Is there a simple way or function to check if the entry to the Editbox is numeric including float numbers. Any alphabetic or alphanumeric entries will not be allowed. Without float number part I would check ascii but I think it does not work for float numbers.

Thanks

Since your question is tagged with mfc , here is a code snippet using CString:

 
 
 
  
  CString ss; float ff; GetDlgItemText(IDC_MY_EDIT_BOX, ss); if (_stscanf_s(ss, _T("%f"), &ff) == 1) // ff contains the value else // error
 
  

If you need to use a double precision number, use "%lf" in the scanf call.

EDIT:

CString ss;
float ff;
GetDlgItemText(IDC_MY_EDIT_BOX, ss);
LPCTSTR lpszString = ss;
TCHAR *endptr;
ff = (float) _tcstod(lpszString, &endptr);
if (endptr != lpszString && *endptr == '\0')
    // ff contains the value
else
    // error

If it is a dialog you can add an edit control to the Dialog. Than Launch the Dialog wizard add a variable to this edit control. Choose type float. The DDX_Text Routine will do the rest.

But this will permit entry of alphabetic chars. If you want to fix this too. You can subclass the edit control with a Special OnChar (WM_CHAR) handler that only allows decimal numbers and the decimal point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM