Can you compare two numbers stored as strings without knowing what type of data they represent?
If I have two numbers represented as strings, "100" and "200", "100.1" and "200.1", how can I compare them to see if they are greater?
Is there a generic Number.Compare (stringA, stringB) that will take care of the data type? I am using a database record to define validation rules, but the values ββcan be long, decimal, floats, etc., so I cannot create any.
source to share
Is there a generic Number.Compare (stringA, stringB) that will take care of the datatype?
No, there is no total comparison number. You must know the type of room. For example. you cannot parse the floating point string "100.1" as an integer. I would like to parse your strings as decimal or two-local (which will handle both "100" and "100.1") and then comparing the results. Use Math.Max to get more out of two numbers:
var max = Math.Max(Double.Parse("100.1"), Double.Parse("200"));
source to share
Easy with linq
var numbers = new string[] { "100" ,"200", "100.1" , "200.1" };
double max = numbers.Max(n => double.Parse(n));
Another solution with simple string manipulation
int N = 100;
var max = numbers.Select(n => n.Split('.'))
.OrderByDescending(p => p[0].PadLeft(N,'0'))
.ThenByDescending(p => p.Length > 1 ? p[1].PadRight(N, '0') : "")
.Select(p => p.Length > 1 ? p[0] + "." + p[1] : p[0])
.First();
source to share
use int.tryParse because it will ensure that if the string is not a number it won't explode
source to share