• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 286
  • Last Modified:

string compare

Hello,
I would like to chek if 3.5 or 5 or 5.5 or 7.8 is less then 4.
How do I do that in C#?
0
johnson1
Asked:
johnson1
3 Solutions
 
Fernando SotoRetiredCommented:
Numerical values or string length. Please be more specific.
0
 
johnson1Author Commented:
I can have a string that is "3.5", "5", "5.5", "7.8", "8" etc.
I need to be able to compare it with the string "4" to know if it is less then 4.
0
 
Fernando SotoRetiredCommented:
Hi johnson1;

You will need to convert your strings to integer data types first then do your comparison. The reason for this is for example lets say you have the following string items, "3.5", "5", "5.5", "7.8", "9", "55", the sort order of this values would be, 3.5, 5, 5.5, 55, 7.8, 9, please note the position of the value "55" it comes before the value of "7.8" numerically that is incorrect but sorting order is correct. Also the equality operators are not support in strings such as <, >, ==, <= and so on and there you would need to use the CompareTo method of the string class which will result in incorrect results as noted above.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Arthur_WoodCommented:
>>You will need to convert your strings to integer data types first then do your comparison<<

not to Integer data type, but to Float or Double (Integers do not have decimal points)

AW
0
 
johnson1Author Commented:
How do I convert "3.5" to integer? Can you please show me an example how I could do the comparison?
0
 
Fernando SotoRetiredCommented:
Thank you Arthur glad someone is keeping me honest. ;=)

This line in my last post , "You will need to convert your strings to integer data types first then do your comparison. ", should read as , "You will need to convert your strings to float or double data types first then do your comparison."
0
 
Fernando SotoRetiredCommented:
Hi johnson1;

As pointed out by Arthur and corrected in my last post that should be float or double. What are your string in, string variable, Array of strings, List<String> ...?
0
 
CM2013Commented:
Use Double.Parse(yourstring) or TryParse method as well - you can handle exceptions in it.

Double d = Double.Parse(s);
if (d<4){}

Is this what you are asking?
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now