如何检查一个变量的内容是否是数字? - 页 5

 
Alain Verleyen:
老实说,我不知道OP的意图。
如果我们把它当作一个一般的请求:"如何检查一个变量的内容是否是数字?",最优雅的解决方案是使用正则表达式。
 
谷歌是你的朋友!这里有一个链接,是用很多很多语言实现 "IsNumeric "的,包括C和C++(但没有MQL)。

这里还有一个似乎更完整的(在页面的最末端)。

Determine if a string is numeric - Rosetta Code
Determine if a string is numeric - Rosetta Code
  • rosettacode.org
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. The first file is the package interface containing the declaration of the Is_Numeric function. The second file is the...
 
Alain Verleyen:
老实说,我不知道OP的意图 ,如果我们把它当作一个一般的请求:"如何检查一个变量的内容是否是数字?",最优雅的解决方案是使用正则表达式。
我的意图就是你所假定的一般要求--如果一个数字是数字,那么它就是数字,可以用于合理的计算,而不会因为数字的性质而产生任何形式的错误。在MQL4中提出一个与正则表达式 有关的示例代码。
 
是的,OP现在就在这里,他听到并看到了迄今为止提出的所有解决方案和反方案。我感谢所有评论者的努力。我喜欢honest_knave提出的示例代码。首先,他一直都在用代码来支持他的评论。其次,他没有在他的任何例子中硬编码。此外,他的代码很容易照顾到任何形式的零(0、0.0、0.00、.0等),而且很容易理解。我不认为使用StringToDouble()会更好,无论如何。

感谢你们 @ whroeder1, honest_knave, Ernst Van Der Merwe, Alain Verleyen 和 Fernando Carreiro。
 
honest_knave:

所以。

  • 通过引用传递字符串
  • 剥去空白处
  • 剥离','。
  • 检查只有一个'.'
  • 检查'+'或'-'是否只作为第一个字符出现
  • 检查其他每个字符是否是0到9之间的数字

例如

bool IsValidNumber(string &text)
  {
   StringReplace(text," ",NULL);
   StringReplace(text,",",NULL);
   int point_cnt = 0;
   for(int i=StringLen(text)-1; i>=0; i--)
     {
      int this_char = StringGetChar(text,i);
      if(this_char == '.')
        {
         point_cnt++;
         if(point_cnt>1)       return(false);
         if(StringLen(text)<2) return(false);
        }
      else if(this_char == '+' || this_char == '-')
        {
         if(i>0) return(false);
        }
      else if(this_char < '0' || this_char > '9') return(false);
     }
   return(true);
  }

如果它返回真,你就可以将该字符串转换为数字。

但还有一些事情我们需要检查。虽然我们需要检查'+'或'-'是否作为第一个字符出现,但我们也需要检查它是否是单独的。
 
honest_knave:

所以。

  • 通过引用传递字符串
  • 剥去空白处
  • 剥离','。
  • 检查只有一个'.'
  • 检查'+'或'-'是否只作为第一个字符出现
  • 检查其他每个字符是否是0到9之间的数字

例如

bool IsValidNumber(string &text)
  {
   StringReplace(text," ",NULL);
   StringReplace(text,",",NULL);
   int point_cnt = 0;
   for(int i=StringLen(text)-1; i>=0; i--)
     {
      int this_char = StringGetChar(text,i);
      if(this_char == '.')
        {
         point_cnt++;
         if(point_cnt>1)       return(false);
         if(StringLen(text)<2) return(false);
        }
      else if(this_char == '+' || this_char == '-')
        {
         if(i>0) return(false);
        }
      else if(this_char < '0' || this_char > '9') return(false);
     }
   return(true);
  }

如果它返回真,你就可以将该字符串转换为数字。

我似乎已经通过添加/修改代码(方框内的代码)解决了这个问题(独立的'+'或'-')。请看下面的图片。