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

Timothee Cour thelastmammoth at gmail.com
Wed Sep 11 14:10:32 PDT 2013


actually that doesn't work:

assert(!isNumeric(`j`)); //ok
assert(!isNumeric(`i`)); //fails ; i is treated as a complex number but
that's not good behavior as we can't write auto a=i;
assert(isNumeric(`1e2`)); // fails even though we can write auto a=1e2;

In contrast, what I had worked (passes those asserts) but only throws on
certain occasions (doesn't always throw on false).

bool isNumberLitteral(T=double)(string a){
  import std.conv;
  //ugly hack to avoid throwing most of the time;
  if(!a.length||a==".")
    return false;
  string s="0"~a;
  auto x=parse!T(s);
  return s.length==0;
}


I'd like to get a version that never throws.



On Fri, Sep 6, 2013 at 9:38 PM, Jonathan M Davis <jmdavisProg at gmx.com>wrote:

> On Friday, September 06, 2013 21:15:44 Timothee Cour wrote:
> > 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):
>
> You could try std.string.isNumeric.
>
> But it's true that it would be nice to have some sort of counterpart to
> std.conv.to which checked whether a conversion was possible or which
> returned
> its argument via an out parameter and returned whether it succeeded or not
> (or
> something similar) for cases where you need to avoid throwing.
>
> http://d.puremagic.com/issues/show_bug.cgi?id=6840
> http://d.puremagic.com/issues/show_bug.cgi?id=6843
>
> - Jonathan M Davis
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20130911/8e49a272/attachment.html>


More information about the Digitalmars-d-learn mailing list