Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you compare two numbers stored as strings without knowing the datatype 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 which one is bigger?

Is there a generic Number.Compare(stringA, stringB) that will take care of datatype? I am using a database entry to determine validation rules, but the values could be long, decimal, floats, etc, so I can't create a single one.

like image 283
Bob. Avatar asked Jan 22 '13 21:01

Bob.


1 Answers

Easy with linq

var numbers = new string[] {  "100" ,"200", "100.1" , "200.1" };
double max = numbers.Max(n => double.Parse(n));

Another solution with just 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();
like image 103
I4V Avatar answered Sep 30 '22 19:09

I4V