c# - IsNumeric Helper Method for large numbers -


i'm trying create simple helper function determines if number numeric. should able handle 'null', negative numbers, , i'm trying without of vb's isnumeric. , having learned linq, thought perfect.

the other thing i'd able pass string, integer, long, or other type, thinking having 'object' parameter want. sure, convert type string before calling helper method, possible?

here's code have far , need able change parameter! can't imagine wouldn't possible... ideas?

private static bool isnumeric(string input) { if (input == null) throw new argumentnullexception("input"); if (string.isnullorempty(input)) return false;  int periodcount = 0; //accept string w/ 1dec support values w/ float  return input.trim()     .tochararray()     .where(c =>     {       if (c == '.') periodcount++;       return char.isdigit(c) && periodcount <= 1;     })     .count() == input.trim().length; } 

there several things @ here. first, code won't work decimal. return char.isdigit(c) && periodcount <= 1; should return (char.isdigit(c) || c == '.') && periodcount <= 1;

secondly, entirely possible. makes code accept anything, wanted.

private static bool isnumeric(object input) {     if (input == null) throw new argumentnullexception("input");     string inputstr = input.tostring();     if (string.isnullorempty(inputstr)) return false;      int periodcount = 0; //accept string w/ 1dec support values w/ float      return inputstr.trim()         .tochararray()         .where(c =>         {             if (c == '.') periodcount++;             return (char.isdigit(c) || c == '.') && periodcount <= 1;         })         .count() == inputstr.trim().length; } 

however, it's complicated. simpler way

private static bool isnumeric(object input) {     if (input == null) throw new argumentnullexception("input");     double test;     return double.tryparse(input.tostring(), out test); } 

Comments

Popular posts from this blog

c++ - Function signature as a function template parameter -

algorithm - What are some ways to combine a number of (potentially incompatible) sorted sub-sets of a total set into a (partial) ordering of the total set? -

How to call a javascript function after the page loads with a chrome extension? -