September 07, 2013 nothrow function to tell if a string can be converted to a number? | ||||
---|---|---|---|---|
| ||||
Attachments:
| 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; } |
Copyright © 1999-2021 by the D Language Foundation