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.
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"));
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();
This will also work if you declared the type as decimal
, even if numbers do not have a decimal point
as if it had decimal point
, this will work too
var strNumbers = new string[]
{
"100",
"200",
"100.1",
"200.1"
};
decimal maxVal = numbers.Max(m => decimal.Parse(m));
Any number represented as a string must be converted to double.
You take them apart. Either with a pre-existing parser or manually, and later MAY BE TRICKY because yo ustand up and say formatting might ever be, which might be scientific notation.
use int.tryParse because it will ensure that if the string is not a number it won't explode