Bob.
Bob.

Reputation: 4002

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.

Upvotes: 10

Views: 22107

Answers (6)

I4V
I4V

Reputation: 35373

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();

Upvotes: 8

MethodMan
MethodMan

Reputation: 18863

This will also work if you declared the type as decimal even if the numbers do not have a decimal point just as if one had a decimal point this will work as well

var strNumbers = new string[] 
{ 
   "100", 
   "200",
   "100.1", 
   "200.1" 
};
decimal maxVal = numbers.Max(m => decimal.Parse(m));

Upvotes: 3

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

Is there a generic Number.Compare(stringA, stringB) that will take care of datatype?

No, there is no generic number comparison. You should know type of number. E.g. you can't parse string with floating point number "100.1" as integer. I'd go with parsing your strings as decimals or doubles (which will handle both "100" and "100.1"), and then comparing results. Use Math.Max to get larger from two numbers:

var max = Math.Max(Double.Parse("100.1"), Double.Parse("200"));

Upvotes: 3

TomTom
TomTom

Reputation: 62159

You parse them. Either with an already existing parser, or manually, and the later MAY BE TRICKY because yo ustand up and tell me the formatting may be everthing, which could be scientific notation.

Upvotes: 0

James Curran
James Curran

Reputation: 103605

Any number represented as a string should be convertable to a double.

Upvotes: 0

muchObliged
muchObliged

Reputation: 45

use int.tryParse because this will ensure that if the string is not a number it will not blow up

Upvotes: -1

Related Questions