nothrow function to tell if a string can be converted to a number?

Timothee Cour thelastmammoth at gmail.com
Fri Sep 6 21:15:44 PDT 2013


I'd like to have a function:

@nothrow bool isNumberLitteral(string a);
unittest{
  assert(isNumberLitteral("1.2"));
  assert(!isNumberLitteral("a1.2"));
  assert(!isNumberLitteral("a.b"));
}

I want it nothrow for efficiency (I'm using it intensively), and try/catch
as below has significant runtime overhead (esp when the exception is
caught):


bool isNumberLitteral(string a){//slow because throws
try{
import std.conv:to;
auto ret=a.to!double;
}
catch
return false;
return true;
}

even this can throw, eg on "a.b" (and uses gc)
bool isNumberLitteral(T=double)(string a){
  import std.conv;
  //ugly hack to avoid throwing;
  if(!a.length||a==".")
  return false;
  string s="0"~a;
  auto x=parse!T(s);
  return s.length==0;
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20130906/c66162bc/attachment-0001.html>


More information about the Digitalmars-d-learn mailing list